螺旋矩阵~

简介: 螺旋矩阵~
class Solution {

    public List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> order = new ArrayList<Integer>();

        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){

            return order;

        }

        int rows = matrix.length;

        int colums = matrix[0].length;

        int left = 0, right = colums-1,top = 0 , bottom = rows-1;

        while(left<=right && top <= bottom ){

            for (int column = left; column <= right;column++){

                order.add(matrix[top][column]);

            }

            for(int row = top+1; row<=bottom; row++){

                order.add(matrix[row][right]);

            }

            // 检查是否需要继续遍历,如果当前区域不是一个行或列,则执行内部的遍历。

            if(left<right && top<bottom){

                //  从右到左遍历当前下边界,将元素添加到列表中

                for(int column = right-1 ; column>left ; column--){

                    order.add(matrix[bottom][column]);

                }

                for(int row = bottom; row>top; row--){

                    order.add(matrix[row][left]);

                }

            }

            // 更新边界值,缩小遍历区域。

            left++;

            right--;

            top++;

            bottom--;

        }

        //  返回按照螺旋顺序遍历矩阵后得到的整数列表

        return order;

    }

}


相关文章
|
2月前
|
存储 算法
LeetCode第54题螺旋矩阵
LeetCode第54题"螺旋矩阵"的解题方法,通过模拟从外到内的螺旋遍历过程,并利用方向向量控制遍历方向的转换,有效输出矩阵的螺旋顺序。
LeetCode第54题螺旋矩阵
|
2月前
|
算法
LeetCode第59题螺旋矩阵 II
LeetCode第59题"螺旋矩阵 II"的解题方法,通过模拟螺旋填充过程,一圈一圈从外到内按顺序填充数字,直到完成整个矩阵的构建。
LeetCode第59题螺旋矩阵 II
|
4月前
18.四数之和
18.四数之和
|
4月前
|
C++
【洛谷 P1706】全排列问题 题解(全排列)
该问题要求按字典序输出从1到n的所有不重复排列。输入为整数n,输出为每行一个的数字序列,每个数字占5个宽度。样例输入3,输出6行全排列。代码使用C++,通过`next_permutation`函数生成所有排列。注意n的范围是1到9。
25 0
|
5月前
18. 四数之和
18. 四数之和
37 2
|
5月前
leetcode-54:螺旋矩阵
leetcode-54:螺旋矩阵
37 0
|
5月前
|
Java C++ Python
leetcode-59:螺旋矩阵 II
leetcode-59:螺旋矩阵 II
31 0
|
算法 安全 Swift
LeetCode - #54 螺旋矩阵
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。
LeetCode - #54 螺旋矩阵
|
算法 安全 Swift
LeetCode - #59 螺旋矩阵 II
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。
LeetCode - #59 螺旋矩阵 II
【AcWing】单调栈
我的评价是:使用栈是真的妙
55 0
【AcWing】单调栈