Spiral Order Matrix II

Given an integer A, generate a square matrix filled with elements from 1 to A2 in spiral order.

Input Format:

The first and the only argument contains an integer, A.

Output Format:

Return a 2-d matrix of size A x A satisfying the spiral order.

Constraints:

1 <= A <= 1000

Examples:

Input 1:
    A = 3

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

Input 2:
    4

Output 2:
    [   [1, 2, 3, 4],
        [12, 13, 14, 5],
        [11, 16, 15, 6],
        [10, 9, 8, 7]   ]
public class Solution {
    public int[][] generateMatrix(int A) {
        int rowstart = 0;
        int rowend = A - 1;
        int colstart = 0;
        int colend = A - 1;
        int value = 1;
        int[][] ans = new int[A][A];
        while (rowstart <= rowend && colstart <= colend) {
            for (int i = colstart; i <= colend; i++) {
                ans[rowstart][i] = value;
                value++;
            }
            rowstart++;
            for (int i = rowstart; i <= rowend; i++) {
                ans[i][colend] = value;
                value++;
            }
            colend--;
            if (rowstart <= rowend) {
                for (int i = colend; i >= colstart; i--) {
                    ans[rowend][i] = value;
                    value++;
                }
                rowend--;
            }
            if (colstart <= colend) {
                for (int i = rowend; i >= rowstart; i--) {
                    ans[i][colstart] = value;
                    value++;
                }
                colstart++;
            }
        }
        return ans;
    }
}

Last updated