题解 | #迷宫问题#

迷宫问题

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})`);
    });
})();

全部评论

相关推荐

05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
点赞 评论 收藏
分享
重生我想学测开:嵌入式的问题,我准备入行京东外卖了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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