题解 | #螺旋矩阵#
螺旋矩阵
https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
import java.util.*; public class Solution { public ArrayList<Integer> spiralOrder (int[][] matrix) { // write code here ArrayList<Integer> res = new ArrayList<>(); if(matrix.length == 0) return res; // 定义四个指针,并且充当边界限制的作用 int top = 0, bottom = matrix.length-1; int left = 0, right = matrix[0].length-1; while(true){ //上面 左到右 for(int i = left; i <= right; i++){ res.add(matrix[top][i]); } ++top; if(top > bottom) break; //右边 上到下 for(int i = top; i <= bottom; i++){ res.add(matrix[i][right]); }--right; if(right < left) break; //下面 右到左 for(int i = right; i>=left; i--){ res.add(matrix[bottom][i]); }--bottom; if(bottom < top) break; //左边 下到上 for(int i = bottom; i>=top; i--){ res.add(matrix[i][left]); }left++; if(left > right) break; } return res; } }