54. 螺旋矩阵https://leetcode.cn/problems/spiral-matrix/
给你一个
m
行n
列的矩阵matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]
算法思路:
对于每层,从左上方开始以顺时针的顺序遍历所有元素。假设当前层的左上角位于 (top,left)右下角位于 (bottom,right),按照如下顺序遍历当前层的元素。
1.从左到右遍历上侧元素,依次为(top,lef) 到 (top,right)。
2.从上到下遍历右侧元素,依次为 (top + 1,right) 到 (bottom,right)。
3.如果 left< right 且 top < bottom,则从右到左遍历下侧元素,依次为 (bottom,right-1)到 (bottom, left+1),以及从下到上遍历左侧元素,依次为 (bottom,let) 到 (top +1, left)
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res=new ArrayList<>();
int left=0,right=matrix[0].length-1,top=0,bottom=matrix.length-1;
while(true){
for(int i=left;i<=right;i++){
res.add(matrix[top][i]);
}
if(++top>bottom){break;}
for(int i=top;i<=bottom;i++){
res.add(matrix[i][right]);
}
if(--right<left){break;}
for(int i=right;i>=left;i--){
res.add(matrix[bottom][i]);
}
if(--bottom<top){break;}
for(int i=bottom;i>=top;i--){
res.add(matrix[i][left]);
}
if(++left>right){break;}
}
return res;
}
}