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 = 4,
[ [1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7] ]
Java代码:
public int[][] generateMatrix(int n) {
if (n < 0) {
return null;
}
int[][] result = new int[n][n];
int xStart = 0;
int yStart = 0;
int num = 1;
while (n > 0) {
if (n == 1) {
result[yStart][xStart] = num++;
break;
}
//top - move right
for (int i = 0; i < n - 1; i++) {
result[xStart][yStart++] = num++;
}
//right - move down
for (int i = 0; i < n - 1; i++) {
result[xStart++][yStart] = num++;
}
//bottom - move left
for (int i = 0; i < n - 1; i++) {
result[xStart][yStart--] = num++;
}
//left - move up
for (int i = 0; i < n - 1; i++) {
result[xStart--][yStart] = num++;
}
xStart++;
yStart++;
n = n - 2;
}
return result;
}