题解 | #螺旋矩阵#

螺旋矩阵

https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        //可以按照一层一层的来,转一圈,就把矩阵剥离了一层
        
        ArrayList<Integer> res = new ArrayList<>();
        if ( matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return res;
        }
        int row = matrix.length, column = matrix[0].length;
        // 四个顶角
        int left = 0, top = 0, right = column - 1, bottom = row - 1;
        while ( left <= right && top <= bottom) {
            // 第一行
            for (int i = left ; i <= right; i++) {
                res.add(matrix[top][i]);
            }
            top++;
            // 最后一列
            for (int i = top; i <= bottom; i++) {
                res.add(matrix[i][right]);
            }
            right--;

            //  此处要再次判断一下顶角问题,因为把上方和右侧方剥离,可能就结束了,这样会重复添加元素
            if (left <= right && top <= bottom) {
                // 最后一行
                for (int i = right; i >= left; i--) {
                    res.add(matrix[bottom][i]);
                }
                bottom--;
                // 第一列
                for (int i = bottom; i >= top; i--) {
                    res.add(matrix[i][left]);
                }
                left++;
            }

        }
        return res;
    }

}

思路:首先要清楚螺旋矩阵,是怎么解开的,就是顺时针,一层一层剥离。因为可以进行迭代。用递归太耗时了。先固定四个顶点,left,right,top,bottom,然后一层while剥离顶行和最右列,再次检测四个顶点的满足条件,如果满足,再剥离底行和最左列,一层弄完,继续while循环。

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务