题解 | #螺旋矩阵#
螺旋矩阵
https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
import java.util.*;
public class Solution {
//分层进行模拟,定位四个方向进行缩小
public ArrayList<Integer> spiralOrder (int[][] matrix) {
// write code here
ArrayList<Integer> ret = new ArrayList<>();
int n = matrix.length;
if(n==0){ //存在数组未空
return ret;
}
int m = matrix[0].length;
if(m==0) return ret;
int top = 0, bottom = n-1, left =0,right = m-1;
//遍历到最后一个
while(left <=right && top <= bottom){
//上层
for(int i=left;i<=right;i++){
ret.add(matrix[top][i]);
}
//右
for(int i=top+1;i<=bottom;i++){
ret.add(matrix[i][right]);
}
if(left<right && top<bottom){
//下
for(int i=right-1;i>=left;i--){
ret.add(matrix[bottom][i]);
}
//左
for(int i=bottom-1;i>top;i--){
ret.add(matrix[i][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return ret;
}
}


查看12道真题和解析