59. Leetcode: Spiral Matrix II

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

Example 1:

Input: n = 3

Output: [[1,2,3],[8,9,4],[7,6,5]]

/*
59. Spiral Matrix II
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n*n in spiral order.
                     top
                   00 01 02
          left 00 {1, 2, 3} 02 right
               10 {4, 5, 6} 12
               20 {7, 8, 9} 22
                   20 21 22
                    bottom
 */
public class SpiralMatrixII {

    public static int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int left = 0;
        int right = n - 1;
        int top = 0;
        int bottom = n - 1;
        int count = 1;

        while(left <= right) {
            for(int j = left; j <= right; j++) {    // left to right
                matrix[top][j] = count++;
            }
            top++;

            for(int i = top; i <= bottom; i++) {    // top to bottom
                matrix[i][right] = count++;
            }
            right--;

            for(int j = right; j >= left; j--) {    // right to left
                matrix[bottom][j] = count++;
            }
            bottom--;

            for (int i = bottom; i >= top; i--) {   // bottom to up
                matrix[i][left] = count++;
            }
            left++;
        }
        return matrix;
    }

    public static void main(String[] args) {
        int n = 5;
        int[][] matrix = generateMatrix(n);
        for(int[] mat: matrix) {
            System.out.println(Arrays.toString(mat));
        }
    }
}

Complexity Analysis:

Time Complexity: O(n)

Space Complexity: O(1)

 

Leetcode Problem Link:

https://leetcode.com/problems/spiral-matrix-ii/