【力扣】54. 螺旋矩阵

题解:

这里当然就不能只是通过双循环来解题了,因为会烦死。这道题的关键点在于左右边界的确定,参考官方解题法在这里写出我的解题思路。

首先 看图,螺旋且顺时针,所以我们可以先遍历从左至右的,上边界加一向下移,然后从上至下,右边界-1向左移,这样就能保证不再 重复遍历。待到从右至左的时候我们需要判断此时左边界是否小于右边界,上边界是否小于下边界,如果满足条件的话那就证明里面还有元素需要处理,那这个时候就进行从右至左,从下至上的操作。

代码如下:

java 复制代码
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        //1.定义数组用以存放满足条件的元素
        List<Integer> order=new ArrayList<Integer>();
        //2.不满足条件的情况直接返回即可
        if(matrix==null||matrix.length==0||matrix[0].length==0) return order;
        //3.获取到上下左右边界的值
        int row=matrix.length,col=matrix[0].length;
        int left=0,right=col-1,top=0,bottom=row-1;
        while(left<=right&&top<=bottom){
            //从左至右
            for(int i=left;i<=right;i++){
                order.add(matrix[top][i]);
            }
            //从上至下
            for(int i=top+1;i<=bottom;i++){
                order.add(matrix[i][right]);
            }
            if(left<right&&top<bottom){
                //从右至左
                for(int i=right-1;i>left;i--){
                    order.add(matrix[bottom][i]);
                }
                //从下至上
                for(int i=bottom;i>top;i--){
                    order.add(matrix[i][left]);
                }
            }
        left++;
        right--;;
        top++;
        bottom--;
        }
        return order;
    }
}
相关推荐
music&movie42 分钟前
算法工程师认知水平要求总结
人工智能·算法
laocui12 小时前
Σ∆ 数字滤波
人工智能·算法
yzx9910132 小时前
Linux 系统中的算法技巧与性能优化
linux·算法·性能优化
全栈凯哥2 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥2 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu2 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
Humbunklung3 小时前
机器学习算法分类
算法·机器学习·分类
Ai多利3 小时前
深度学习登上Nature子刊!特征选择创新思路
人工智能·算法·计算机视觉·多模态·特征选择
蒟蒻小袁3 小时前
力扣面试150题--被围绕的区域
leetcode·面试·深度优先
Q8137574604 小时前
中阳视角下的资产配置趋势分析与算法支持
算法