题目: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 ]
]
类似于剥洋葱,一圈一圈的写入。设置4个指针,分别是left、right、top、bottom,先写最外圈 第一行->右竖列->最下行->左竖列,然后写倒数第二圈……
public class Solution {
/**
* 简化为剥洋葱的模式,一层一层的剥开
*/
public int[][] generateMatrix(int n) {
int[][]a=new int[n][n];
if(n==0) return a;
int left=0,top=0,right=n-1,bottom=n-1;
int cur=1;
while(left<=right && top<=bottom){
for(int i=left;i<=right;i++){
a[top][i]=cur++;
}
for(int i=top+1;i<=bottom;i++){
a[i][right]=cur++;
}
for(int i=right-1;i>=left;i--){
a[bottom][i]=cur++;
}
for(int i=bottom-1;i>top;i--){
a[i][left]=cur++;
}
left++;
top++;
right--;
bottom--;
}
return a;
}
}