🌕 54. 螺旋矩阵

吞佛童子2022年6月9日
  • algorithm
  • array
小于 1 分钟

🌕 54. 螺旋矩阵

难度: 🌕

问题描述

img_13.png


解法

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        // 思路:
        int rwos = matrix.length;
        int cols = matrix[0].length;

        int left = 0;
        int right = cols - 1;
        int top = 0;
        int bottom = rwos - 1;
        List<Integer> res = new ArrayList<>();
        while(left <= right && top <= bottom) {
            // left -> right
            if(left <= right && top <= bottom) {
                for(int j = left; j <= right; j ++) {
                    res.add(matrix[top][j]);
                } 
            }
            top ++;
            // top -> bottom
            if(left <= right && top <= bottom) {
                for(int i = top; i <= bottom; i ++) {
                    res.add(matrix[i][right]);
                }
            }
            right --;
            // right -> left
            if(left <= right && top <= bottom) {
                for(int j = right; j >= left; j --) {
                    res.add(matrix[bottom][j]);
                }
            }
            bottom --;
            // bottom -> top
            if(left <= right && top <= bottom) {
                for(int i = bottom; i >= top; i --) {
                    res.add(matrix[i][left]);
                }
            }
            left ++;
        }
        return res;
    }
}

输出

img_12.png

上次编辑于: 2022/6/20 下午8:24:47
贡献者: liuxianzhishou