题解 | #迷宫问题#

迷宫问题

https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    // Write your code here
    let index = 0;
    let n, m;
    let matrix = [];
    while ((line = await readline())) {
        let tokens = line.split(" ").map(Number);
        if (index === 0) {
            n = tokens[0];
            m = tokens[1];
            index++;
        } else {
            matrix.push(tokens);
        }
    }
    // 定义四个方向
    const dirs = [
        [0, 1],
        [0, -1],
        [-1, 0],
        [1, 0],
    ];

    function findPath(matrix) {
        const dfs = (matrix, x, y) => {
            let pathList = [];
            // 查找到目标点开始回溯
            if (x === n - 1 && y === m - 1) {
                return [[x, y]];
            }
            // 每次查找后将值置为1
            matrix[x][y] = 1;
            for (const [dx, dy] of dirs) {
                const row = x + dx;
                const col = y + dy;
                // 索引越界跳过
                if (row < 0 || row >= n || col < 0 || col >= m) continue;
                // 值为墙跳过
                if (matrix[row][col] === 1) continue;
                pathList = dfs(matrix, row, col);
                // 长度不为0表示已经查找到终点,将终点的上一个回溯点入队
                if (pathList.length !== 0) {
                    pathList.unshift([x, y]);
                    return pathList;
                }
            }
            return pathList;
        };
        return dfs(matrix, 0, 0);
    }

    const pathList = findPath(matrix);
    pathList.forEach(([x, y]) => {
        console.log(`(${x},${y})`);
    });
})();

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 18:05
哈哈哈哈哈感觉朋友找工作的已经疯掉了,直接上图
码农索隆:真老板娘:“我嘞个去,这不我当年的套路吗
点赞 评论 收藏
分享
求offer的大角牛:不吃香菜
点赞 评论 收藏
分享
06-12 16:00
天津大学 Java
牛客30236098...:腾讯坏事做尽,终面挂是最破防的 上次被挂了后我连简历都不刷了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务