题解 | 迷宫问题

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

void (async function () {
    const [rowLength, columnLength] = (await readline()).split(" ").map(Number);
    const maze = [];
    for (let i = 0; i < rowLength; i++) {
        maze.push((await readline()).split(" ").map(Number));
    }
    // console.log(maze)
    const directions = [
        [-1, 0],
        [1, 0],
        [0, -1],
        [0, 1],
    ];
    const queue = [];
    const parent = [];
    queue.push([0, 0]);
    for (let i = 0; i < rowLength; i++) {
        parent[i] = new Array(columnLength).fill(null);
    }
    // console.log(parent)
    while (queue.length > 0) {
        const [x, y] = queue.shift();
        for ([dx, dy] of directions) {
            const nextX = x + dx;
            const nextY = y + dy;
            if (
                nextX >= 0 &&
                nextX < rowLength &&
                nextY >= 0 &&
                nextY < columnLength &&
                maze[nextX][nextY] === 0 &&
                parent[nextX][nextY] === null
            ) {
                parent[nextX][nextY] = [x, y];
                queue.push([nextX, nextY]);
            }
        }
        if (x === rowLength - 1 && y === columnLength - 1) {
            const path = [];
            let currentX = x,
                currentY = y;
            while (currentX !== 0 || currentY !== 0) {
                path.push([currentX, currentY]);
                [currentX, currentY] = parent[currentX][currentY];
            }
            path.push([0, 0]);
            path.reverse();
            for (const [px, py] of path) {
                console.log(`(${px},${py})`);
            }
            return;
        }
    }
})();

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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