Java Solution Clean and Concise


  • 1
    N
    public int[][] generateMatrix(int n) {
            if (n < 1) return new int[n][n];
            int[][] matrix = new int[n][n];
            int[][] d = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
            int i = 0, j = 0, dir = 0; // dir = 0 (right), 1 (down), 2 (left), 3 (up)
            for (int k = 1; k <= n * n; k++) {
                matrix[i][j] = k;
                if (i + d[dir][0] == n || i + d[dir][0] < 0 || j + d[dir][1] == n || j + d[dir][1] < 0 || matrix[i + d[dir][0]][j + d[dir][1]] != 0) {
                    dir = (dir + 1) % 4;
                }
                i += d[dir][0];
                j += d[dir][1];
            }
            return matrix;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.