螺旋数组题解

题目链接:

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
};
相关推荐
E***U9451 小时前
前端安全编程实践
前端·安全
老华带你飞1 小时前
海产品销售系统|海鲜商城购物|基于SprinBoot+vue的海鲜商城系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·毕设·海鲜商城购物系统
x***B4112 小时前
React安全编程实践
前端·安全·react.js
D***t1312 小时前
前端微服务案例
前端
czlczl200209252 小时前
算法:二叉树的公共祖先
算法
哀木2 小时前
诶,这么好用的 mock 你怎么不早说
前端
Lear2 小时前
UniApp PDF文件下载与预览功能完整实现指南
前端
Heo2 小时前
关于XSS和CSRF,面试官更喜欢这样的回答!
前端·javascript·面试
7***A4433 小时前
Vue自然语言处理应用
前端·vue.js·自然语言处理