螺旋数组题解

题目链接:

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
};
相关推荐
子兮曰9 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖9 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神9 小时前
github发布pages的几种状态记录
前端
那个村的李富贵11 小时前
CANN加速下的AIGC“即时翻译”:AI语音克隆与实时变声实战
人工智能·算法·aigc·cann
power 雀儿11 小时前
Scaled Dot-Product Attention 分数计算 C++
算法
不像程序员的程序媛11 小时前
Nginx日志切分
服务器·前端·nginx
北原_春希12 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
尽意啊12 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜12 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive12 小时前
Vue3使用ECharts
前端·javascript·echarts