题目描述:
Given an integer n, generate a square matrix filled with elements from 1 to n 2 in spiral order.
For example,
Given n =3,
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思路解析:
- 要设置每一圈的界限,包括上下左右
- 首先给第一行赋值,向右,此时行为top,列逐渐加一;再给最后一列赋值,向下,此时列为right,行逐渐加一;等
- 每一圈缩小范围,最后如果时奇数的话,需要把最后一个赋值给最中间的数。
代码:
public class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
if(n==0)
return res;
int k=1;
int bottom=n-1,top=0,left=0,right=n-1;
while(left<right&&top<bottom){
for(int i=left;i<right;i++){
res[top][i]=k++;
}
for(int i=top;i<bottom;i++){
res[i][right]=k++;
}
for(int i=right;i>left;i--){
res[bottom][i]=k++;
}
for(int i=bottom;i>top;i--){
res[i][left]=k++;
}
top++;
bottom--;
right--;
left++;
}
if(n%2!=0)
res[n/2][n/2]=k;
return res;
}
}