螺旋数组题解

题目链接:

54. 螺旋矩阵 - 力扣(LeetCode)

思路:

定义顺时针方法的数组:[[0, 1], [1, 0], [0, -1], [-1, 0]] 用一个 变量表示当前的方向,模拟螺旋方位行走。

用 book 数组标记哪些是走过的,哪些没有走过,并且额外判断边界条件,然后针对于此,满足这些条件可以按照当前方位继续走,如果不满足,则先回到原来的位置,然后换个方位继续试探,直到试探到可行条件,需要注意结束条件------满足count计数等于 m*n 的条件 跳出循环

代码:

javascript 复制代码
/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
    let res = [], book = new Array(matrix.length).fill(0).map(
        () => new Array(matrix[0].length).fill(0)
    );

    let curDirect = 0, dict = [[0, 1], [1, 0], [0, -1], [-1, 0]];
    let count = 0, m = matrix.length, n = matrix[0].length;
    let i, j;
    i = j = 0;
    while (count < m * n) {
        while (i >= 0 && i < m && j >= 0 && j < n && book[i][j] === 0) {
            res.push(matrix[i][j])
            book[i][j] = 1
            i += dict[curDirect][0]
            j += dict[curDirect][1]
            count++
        }

        if (count === m * n) {
            break;
        }

        while (i < 0 || i >= m || j < 0 || j >= n || book[i][j]) {
            // 先回到原位置
            i -= dict[curDirect][0]
            j -= dict[curDirect][1]
            curDirect = (curDirect + 1) % 4
            i += dict[curDirect][0]
            j += dict[curDirect][1]

        }

    }

    return res
};
相关推荐
超级码力6665 小时前
【Latex文件架构】Latex文件架构模板
算法·数学建模·信息可视化
ZC跨境爬虫5 小时前
跟着 MDN 学 HTML day_9:(信件语义标记)
前端·css·笔记·ui·html
穿条秋裤到处跑5 小时前
每日一道leetcode(2026.04.29):二维网格图中探测环
算法·leetcode·职场和发展
前端老石人5 小时前
HTML 字符引用完全指南
开发语言·前端·html
Merlos_wind6 小时前
HashMap详解
算法·哈希算法·散列表
幼儿园技术家6 小时前
前端如何设计权限系统(RBAC / ABAC)?
前端
汉克老师6 小时前
GESP2025年3月认证C++五级( 第三部分编程题(1、平均分配))
c++·算法·贪心算法·排序·gesp5级·gesp五级
前端摸鱼匠7 小时前
Vue 3 的v-bind合并行为:讲解v-bind与普通属性合并的规则
前端·javascript·vue.js·前端框架·ecmascript
REDcker8 小时前
浏览器端Web程序性能分析与优化实战 DevTools指标与工程清单
开发语言·前端·javascript·vue·ecmascript·php·js
Yzzz-F9 小时前
Problem - 2205D - Codeforces
算法