0
点赞
收藏
分享

微信扫一扫

LeetCode-059-螺旋矩阵 II

书呆鱼 2021-09-28 阅读 50
LeetCode

螺旋矩阵 II

解法一:数组遍历
public class LeetCode_059 {
    public static int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        boolean[][] flag = new boolean[n][n];
        int i = 0, j = -1, count = 0;
        while (count < n * n) {
            // 向右
            while (j + 1 < n && !flag[i][j + 1] && count < n * n) {
                j = j + 1;
                count++;
                result[i][j] = count;
                flag[i][j] = true;
            }

            // 向下
            while (i + 1 < n && !flag[i + 1][j] && count < n * n) {
                i = i + 1;
                count++;
                result[i][j] = count;
                flag[i][j] = true;
            }

            // 向左
            while (j - 1 >= 0 && !flag[i][j - 1] && count < n * n) {
                j = j - 1;
                count++;
                result[i][j] = count;
                flag[i][j] = true;
            }

            // 向上
            while (i - 1 >= 0 && !flag[i - 1][j] && count < n * n) {
                i = i - 1;
                count++;
                result[i][j] = count;
                flag[i][j] = true;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        for (int[] ints : generateMatrix(4)) {
            for (int anInt : ints) {
                System.out.print(anInt + "\t");
            }
            System.out.println();
        }
    }
}
举报

相关推荐

0 条评论