题解 | #螺旋矩阵#
螺旋矩阵
https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(matrix.length == 0) return res;
//分别记录上、下、左、右边界
int up = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
while(up < (matrix.length + 1)/2 && left < (matrix[0].length + 1)/2){
//顺时针填充
//1.填充上边界
for(int i = left ; i <= right ; i++){
res.add(matrix[up][i]);
}
//2.填充右边界
for(int i = up + 1 ; i <= bottom ; i++){
res.add(matrix[i][right]);
}
//3.填充下边界
for(int i = right - 1 ; up != bottom && i >= left ; i--){
res.add(matrix[bottom][i]);
}
//4.填充左边界
for(int i = bottom - 1 ; left != right && i >= up + 1 ; i--){
res.add(matrix[i][left]);
}
up++;
bottom--;
left++;
right--;
}
return res;
}
}

