Question

link

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 ]
]

Stats

Frequency 2
Difficulty 3
Adjusted Difficulty 3
Time to use --------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

This question is basic mathematics. There is another similar question [LeetCode 54] Spiral Matrix.

The difficult part is writing the code.

My code

Updated on Oct 9th, 2014:

public int[][] generateMatrix(int n) {
    int small = 0;
    int large = n - 1;
    int num = 1;

    int[][] ans = new int[n][n];
    while (small < large) {
        for (int i = small; i < large; i++) {
            ans[small][i] = num++;
        }
        for (int i = small; i < large; i++) {
            ans[i][large] = num++;
        }
        for (int i = large; i > small; i--) {
            ans[large][i] = num++;
        }
        for (int i = large; i > small; i--) {
            ans[i][small] = num++;
        }
        small++;
        large--;
    }
    if (small == large) {
        ans[small][small] = num;
    }
    return ans;
}