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 ]
]
此题与Spiral Matrix类似,可以用相同的方法解决,相比之下,此题比前一题简单
public class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix=new int[n][n];
int temprow=n;
int tempcol=n;
int start =-1;
int end=-1;
int t=1;
while(temprow>0&&tempcol>0){
start++;
end++;
for(int i=start;i<tempcol;i++){
matrix[start][i]=t;
t++;
}for(int j=start+1;j<temprow;j++){
matrix[j][tempcol-1]=t;
t++;
}
for(int x=tempcol-2;x>=end;x--){
matrix[temprow-1][x]=t;
t++;
}for(int y=temprow-2;y>start;y--){
matrix[y][end]=t;
t++;
}temprow=temprow-1;
tempcol=tempcol-1;
}
return matrix;}
}
【LeetCode】Spiral Matrix II,布布扣,bubuko.com
时间: 2024-12-26 11:38:43