螺旋数组题解

题目链接:

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
};
相关推荐
董董灿是个攻城狮1 小时前
大模型连载2:初步认识 tokenizer 的过程
算法
Kagol2 小时前
🎉OpenTiny NEXT-SDK 重磅发布:四步把你的前端应用变成智能应用!
前端·开源·agent
地平线开发者2 小时前
地平线 VP 接口工程实践(一):hbVPRoiResize 接口功能、使用约束与典型问题总结
算法·自动驾驶
罗西的思考2 小时前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
GIS之路3 小时前
ArcGIS Pro 中的 notebook 初识
前端
JavaGuide3 小时前
7 道 RAG 基础概念知识点/面试题总结
前端·后端
ssshooter3 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
格砸4 小时前
从入门到辞职|从ChatGPT到OpenClaw,跟上智能时代的进化
前端·人工智能·后端
Live000005 小时前
在鸿蒙中使用 Repeat 渲染嵌套列表,修改内层列表的一个元素,页面不会更新
前端·javascript·react native
柳杉5 小时前
使用Ai从零开发智慧水利态势感知大屏(开源)
前端·javascript·数据可视化