LeetCode 54. 螺旋矩阵
题目描述
解题思路
遍历。
参考 labuladong的算法小抄.
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int row = matrix.length, col = matrix[0].length;
//上边界 upper_bound 下边界 low_bound
int upper_bound = 0, low_bound = row - 1;
//左边界 left_bound 右边界 right_bound
int left_bound = 0, right_bound = col - 1;
while(res.size() < row * col){
//从左到右遍历(顶部 upper_bound) left_bound -> right_bound
if(upper_bound <= low_bound){
for(int j = left_bound; j <= right_bound; j ++){
res.add(matrix[upper_bound][j]);
}
upper_bound ++;
}
//从上到下遍历(右侧 right_bound) upper_bound -> low_bound
if(left_bound <= right_bound){
for(int i = upper_bound; i <= low_bound; i ++){
res.add(matrix[i][right_bound]);
}
right_bound --;
}
//从右到左遍历(底部 low_bound) right_bound -> left_bound
if(upper_bound <= low_bound){
for(int j = right_bound; j >= left_bound; j --){
res.add(matrix[low_bound][j]);
}
low_bound --;
}
//从下到上遍历(左侧 left_bound) low_bound -> upper_bound
if(left_bound <= right_bound){
for(int i = low_bound; i >= upper_bound; i --){
res.add(matrix[i][left_bound]);
}
left_bound ++;
}
}
return res;
}
}