螺旋矩阵
给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
#思路
定义left,right,top,down为四个边界。
left = 0,right = n - 1, top = 0, down = n - 1;
每当移动到边界时,需要改变边界条件。
比如当向右移动到边界时,应向下继续移动,则top需要向下移一位。
for(int i = l; i <= r;i++) res[t][i] = count++; t ++;
while循环控制条件 count <=target
class Solution {
public int[][] generateMatrix(int n) {
int l = 0, r = n - 1, t = 0, d = n - 1;
int[][] res = new int[n][n];
int target = n*n;
int count = 1;
while(count <= target){
for(int i = l; i<= r;i++) { res[t][i] = count++;}
t++;
for(int i = t; i <= d;i++) { res[i][r] = count++; }
r--;
for(int i = r; i >= l;i--) { res[d][i] = count++;}
d--;
for(int i = d; i >= t;i--) { res[i][l] = count++;}
l++;
}
return res;
}
}
浙公网安备 33010602011771号