前言
记录跟着“代码随想录”刷力扣的过程
链接: 代码随想录
数组部分(二)
六、螺旋矩阵II
59.螺旋矩阵II
思路:设置计数器count,count>n*n时结束循环。
初始时,第0行为上边界,第n-1行为下边界,下标0为左边界,下标n-1为右边界。自左向右填充完后,行的上边界+1;然后自上往下填充,右边界-1;然后自右向左填充,下边界-1;然后自下而上填充,左边界+1。
class Solution {
public int[][] generateMatrix(int n) {
int[][] m=new int[n][n];
int count=1;
int top=0,bottom=n-1,left=0,right=n-1;
while(count<=n*n){
for(int i=left;i<=right;i++) m[top][i]=count++;
top--;
for(int i=top;i<=bottom;i++) m[i][right]=count++;
right--;
for(int i=right;i>=left;i--) m[bottom][i]=count++;
bottom--;
for(int i=bottom;i>=top;i--) m[i][left]=count++;
left--;
}
return m;
}
}
54. 螺旋矩阵
注意点:因为题目要求 m 行 n 列的矩阵 matrix 不一定是方阵。上一题中方阵的left>right时,top>bottom,反之一样,所以不会出现重复读的情况。但不是方阵时,当 top>bottom时,left不一定大于right,可能重复读,所以需要读完某一列(行)后判断整个矩阵是否已经读完。
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int m=matrix.length,n= matrix[0].length;
ArrayList<Integer> list = new ArrayList<>();
int left=0,right=n-1,top=0,bottom=m-1;
while(true){
for(int i=left;i<=right;i++) {
list.add(matrix[top][i]);
}
top++;
if(top>bottom) break;
for(int i=top;i<=bottom;i++) {
list.add(matrix[i][right]);
}
right--;
if(right<left) break;
for(int i=right;i>=left;i--) {
list.add(matrix[bottom][i]);
}
bottom--;
if(bottom<top) break;
for(int i=bottom;i>=top;i--) {
list.add(matrix[i][left]);
}
left++;
if(left>right) break;
}
return list;
}
}