【LeetCode-中等题】54. 螺旋矩阵

文章目录

题目

方法一:按层模拟

思路就是定义四个指针边界,按顺序扫完一遍,再缩小区域再扫描

java 复制代码
 public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> order = new ArrayList<Integer>(); 
        int matrixlength = matrix.length;
        int matrixNumlength = matrix[0].length;
        //判空条件
        if(matrix==null ||  matrixlength == 0 || matrixNumlength == 0) return order;
        //定义四个指针边界
        int top = 0;//行边界
        int bot = matrixlength-1;
        int left = 0;//列边界
        int right = matrixNumlength-1;
        while(left <= right && top <= bot){
        // 首先循环最外层  顺序依次为右下左上
           // (left)                   (right)
        // (top)1,      2,      3,       4 (top)
        //      5,      6,      7,       8
        // (bot)9,      10,     11,     12(bot)
           // (left)                    (right)

        //右 -->  左  最上层
        for(int i = left ;i <= right;i++){
            order.add(matrix[top][i]);
        }

         //上 -->  下  最右层
        for(int i = top+1 ;i <= bot;i++){
            order.add(matrix[i][right]);
        }
    if(left!=right  && bot!=top){//  如果right和left重合了  说明上往下扫描了一遍,就不需要再从下往上重复扫一遍了
                                //  如果 bot 和 top 重合了  说明左往右扫描了一遍,就不需要再从右往左重复扫一遍了
         //左 -->  右  最下层
        for(int i = right-1 ;i >= left;i--){
            order.add(matrix[bot][i]);
        }
  
          //下 -->  上  最左层
        for(int i = bot-1 ;i >top;i--){
            order.add(matrix[i][left]);
        }
  }    
        //往里缩一圈
        left  ++;
        right --;
        top ++;
        bot --;
        }
        return order;
    }
相关推荐
晚霞的不甘2 分钟前
Flutter for OpenHarmony 可视化教学:A* 寻路算法的交互式演示
人工智能·算法·flutter·架构·开源·音视频
望舒5135 分钟前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
C++ 老炮儿的技术栈20 分钟前
Qt 编写 TcpClient 程序 详细步骤
c语言·开发语言·数据库·c++·qt·算法
KYGALYX25 分钟前
逻辑回归详解
算法·机器学习·逻辑回归
铉铉这波能秀33 分钟前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
参.商.34 分钟前
【Day 27】121.买卖股票的最佳时机 122.买卖股票的最佳时机II
leetcode·golang
踢足球092937 分钟前
寒假打卡:2026-2-8
数据结构·算法
IT猿手1 小时前
基于强化学习的多算子差分进化路径规划算法QSMODE的机器人路径规划问题研究,提供MATLAB代码
算法·matlab·机器人
千逐-沐风1 小时前
SMU-ACM2026冬训周报3rd
算法
铉铉这波能秀1 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple