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 ]
]
Solution:
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
if (n == 0) {
return result;
}
int rowBegin = 0;
int rowEnd = n - 1;
int colBegin = 0;
int colEnd = n - 1;
int i = 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
for (int j = colBegin; j <= colEnd; j++) {
result[rowBegin][j] = i++;
}
rowBegin++;
for (int j = rowBegin; j <= rowEnd; j++) {
result[j][colEnd] = i++;
}
colEnd--;
if (rowBegin <= rowEnd) {
for (int j = colEnd; j >= colBegin; j--) {
result[rowEnd][j] = i++;
}
}
rowEnd--;
if (colBegin <= colEnd) {
for (int j = rowEnd; j >= rowBegin; j--) {
result[j][colBegin] = i++;
}
}
colBegin++;
}
return result;
}