-
2.10
- 四个边界都是闭区间,所以 for 循环里=也符合条件
- 其他逻辑都想起来了
-
1.24
- 维护左右上下四个墙壁指针,根据指针开始螺旋
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if(matrix==null||matrix.length==0) return res;
int top=0,bottom=matrix.length-1;
int left=0,right=matrix[0].length-1;
while(top<=bottom&&left<=right){
for(int i=left;i<=right;i++){
res.add(matrix[top][i]);
}
top++;
for(int i=top;i<=bottom;i++){
res.add(matrix[i][right]);
}
right--;
if(top<=bottom){
for(int i=right;i>=left;i--){
res.add(matrix[bottom][i]);
}
bottom--;
}
if(left<=right){
for(int i=bottom;i>=top;i--){
res.add(matrix[i][left]);
}
left++;
}
}
return res;
}
}后两步需要判断,因为“上→下”后边界已经缩了, 可能出现 “单行” 或 “单列” 的情况。 防止重复访问同一行/列