LeetCode

Spiral Matrix II

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

For example,
Given n = 3,

You should return the following matrix:

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

Java

public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int count = 1;
        int x = 0, y = 0;

        while(n > 0) {
            if(n == 1) {
                matrix[x][y] = count;
            }

            for(int i = 0; i < n - 1; i++) {
                matrix[x][y++] = count++;
            }
            for(int i = 0; i < n - 1; i++) {
                matrix[x++][y] = count++;
            }
            for(int i = 0; i < n - 1; i++) {
                matrix[x][y--] = count++;
            }
            for(int i = 0; i < n - 1; i++) {
                matrix[x--][y] = count++;
            }
            x++;
            y++;
            n -= 2;
        }
        return matrix;
    }
}