问题:
Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
解决:
① 与Spiral Matrix相同的遍历方法,只是将每个位置的值设置为1~n^2.
class Solution { //2ms
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int top = 0;
int left = 0;
int bottom = n - 1;
int right = n - 1;
int val = 1;
while(left <= right && top <= bottom) {
for (int i = left;i <= right ;i ++ ) {
res[top][i] = val ++;
}
for (int i = top + 1;i <= bottom - 1 ;i ++ ) {
res[i][right] = val ++;
}
if(top != bottom){
for (int i = right;i >= left ;i -- ) {
res[bottom][i] = val ++;
}
}
if (left != right) {
for (int i = bottom - 1;i >= top + 1 ;i -- ) {
res[i][left] = val ++;
}
}
left ++;
right --;
top ++;
bottom --;
}
return res;
}
}