博客
关于我
给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。
阅读量:374 次
发布时间:2019-03-05

本文共 1929 字,大约阅读时间需要 6 分钟。

二维数组的顺时针螺旋遍历是一种常见的算法问题,主要用于遍历矩阵中的元素按照特定顺序排列。以下是优化后的详细解释和解决方案:

理解顺时针螺旋遍历

顺时针螺旋遍历的核心思想是逐层从矩阵的外向内遍历,每一层都按顺时针方向收缩矩阵范围。具体来说,每一层包括四个步骤:

  • 左到右遍历当前层的顶行。
  • 上到下遍历当前层的右列。
  • 右到左遍历当前层的底行。
  • 下到上遍历当前层的左列。
  • 通过逐步收缩矩阵范围(即调整top、bottom、left、right指针),可以层层递进地遍历整个矩阵。

    解决方案代码

    import java.util.ArrayList;import java.util.List;public class Solution {    public List
    spiralOrder(int[][] matrix) { List
    res = new ArrayList<>(); if (matrix.length == 0) { return res; } int top = 0; int bottom = matrix.length - 1; int left = 0; int right = matrix[0].length - 1; while (top <= bottom && left <= right) { // 左到右遍历顶行 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 (top <= bottom) { // 确保还有行存在 for (int i = right; i >= left; i--) { res.add(matrix[bottom][i]); } bottom--; } // 下到上遍历左列 if (left <= right) { // 确保还有列存在 for (int i = bottom; i >= top; i--) { res.add(matrix[i][left]); } left++; } } return res; }}

    代码解释

  • 初始化指针topbottomleftright指针分别初始化为矩阵的顶行、底行、左列和右列。
  • 主循环:只要top未超过bottomleft未超过right,继续循环处理每一层。
  • 左到右遍历:遍历当前层的顶行,从左到右依次添加元素到结果列表中,然后将top指针向下移动。
  • 上到下遍历:遍历当前层的右列,从顶行的下一行到底行依次添加元素,然后将right指针向左移动。
  • 右到左遍历:如果还有行存在,遍历当前层的底行,从右到左依次添加元素,然后将bottom指针向上移动。
  • 下到上遍历:如果还有列存在,遍历当前层的左列,从底行向上依次添加元素,然后将left指针向右移动。
  • 测试案例

    假设输入矩阵为:

    1 2 34 5 67 8 9

    按照上述算法,输出顺序应该是:1, 2, 3, 6, 9, 8, 7, 4, 5。

    优化建议

    • 边界处理:在每一步遍历后,检查是否还有行或列存在,避免重复遍历或越界。
    • 指针调整:每完成一个方向遍历后,相应的指针向内移动,逐步收缩矩阵范围。
    • 清晰的注释:确保代码中有足够的注释,方便其他开发者理解算法逻辑。

    通过以上方法,可以高效地实现二维数组的顺时针螺旋遍历,适用于处理类似的问题。

    转载地址:http://nsog.baihongyu.com/

    你可能感兴趣的文章
    nmap 使用方法详细介绍
    查看>>
    Nmap扫描教程之Nmap基础知识
    查看>>
    nmap指纹识别要点以及又快又准之方法
    查看>>
    Nmap渗透测试指南之指纹识别与探测、伺机而动
    查看>>
    Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.7 Parameters vs Hyperparameters
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>