螺旋数组题解

题目链接:

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
};
相关推荐
alexander0688 小时前
CSS 类选择器组合
前端·css
寅时码13 小时前
React 之死·终章:一个 useRef,把闭包陷阱、依赖数组、漫天 rerender 全送走
前端·react.js·ai编程
不好听61313 小时前
HTML 事件监听机制:从 DOM Level 0 到 React 合成事件
前端·react.js·html
wordbaby14 小时前
为什么刷新页面就 404?聊聊 SPA 路由与 Nginx 的那点事
前端
不好听61314 小时前
React 核心概念:JSX、组件与数据驱动
前端·react.js
触底反弹14 小时前
🔥 React 零基础入门(中):500 行屎山代码到组件化的蜕变
前端·javascript·react.js
不好听61314 小时前
React vs Vue:两大前端框架技术选型深度对比
前端·vue.js·react.js
GuWenyue14 小时前
Cursor黑盒拆解!1套LangChain.js手写Mini编程Agent,自动生成React项目,效率提升60%
前端·数据库·人工智能
GuWenyue14 小时前
传统Agent工具两大痛点!300行代码落地MCP跨语言工具,彻底解耦LLM与工具
前端·人工智能·算法
小林ixn15 小时前
从 onclick 到 React 合成事件,再到完整应用逻辑:一次前端架构的深度剖析
前端·react.js·前端框架