螺旋矩阵 (Spiral Matrix)

 

思路:

// @Title: 螺旋矩阵 (Spiral Matrix)
// @Author: qisiii
// @Date: 2024-05-17 10:36:54
// @Runtime: 0 ms
// @Memory: 40.6 MB
// @comment: 
// @flag: 
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        int top=0,left=0,right=matrix[0].length-1,bottom=matrix.length-1;
        int index=0;
        List<Integer> list=new ArrayList<>();
        int total=matrix.length*matrix[0].length;
        while(index<total){
            for(int i=left;i<=right&&index<total;i++){
                list.add(matrix[top][i]);
                index++;
            }
            top++;
            for(int i=top;i<=bottom&&index<total;i++){
                list.add(matrix[i][right]);
                index++;
            }
            right--;
            for(int i=right;i>=left&&index<total;i--){
                list.add(matrix[bottom][i]);
                index++;
            }
            bottom--;
            for(int i=bottom;i>=top&&index<total;i--){
                list.add(matrix[i][left]);
                index++;
            }
            left++;
        }
        return list;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18