Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
刷第二遍,写完spiral matrix 再写ii的时候, ii 完全可以套用1 的模版
这里主要注意的是 while 循环里 是 top <= bottom, 所以可能存在top ==bottom 的情况,这时候要break
public class Solution {
public int[][] generateMatrix(int n) {
if (n < 0) {
return null;
}
int[][] result = new int[n][n];
int top = 0;
int bottom = n - 1;
int value = 1;
while (top <= bottom ) {
for (int i = top; i <= bottom; i++) {
result[top][i] = value;
value++;
}
for (int i = top + 1; i <= bottom; i++) {
result[i][bottom] = value;
value++;
}
if (top == bottom) {
break;
}
for (int i = bottom - 1; i >= top; i--) {
result[bottom][i] = value;
value++;
}
for (int i = bottom - 1; i > top; i--) {
result[i][top] = value;
value++;
}
top++;
bottom--;
}
return result;
}
}