题解 | #迷宫问题#

迷宫问题

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 count = await readline();
    let [rows, cols] = count.split(" ").map((x) => parseInt(x));
    let maze = [];
    for (let i = 0; i < +rows; i++) {
        let data = await readline();
        maze.push(data.split(" ").map((x) => parseInt(x)));
    }

    const visited = Array.from({ length: rows }, () => Array(cols).fill(false));

    const path = [];

    // 定义方向:上、右、下、左
    const directions = [
        [-1, 0],
        [0, 1],
        [1, 0],
        [0, -1],
    ];

    function dfs(row, col) {
        // 如果到达右下角
        if (row === rows - 1 && col === cols - 1) {
            path.push([row, col]);
            return true;
        }

        // 标记当前位置已访问
        visited[row][col] = true;

        // 尝试四个方向
        for (const [dr, dc] of directions) {
            const newRow = row + dr;
            const newCol = col + dc;

            // 判断新位置是否合法
            if (
                newRow >= 0 &&
                newRow < rows &&
                newCol >= 0 &&
                newCol < cols &&
                maze[newRow][newCol] === 0 &&
                !visited[newRow][newCol]
            ) {
                // 将当前位置加入路径
                path.push([row, col]);

                // 递归进入新位置
                if (dfs(newRow, newCol)) {
                    return true;
                }

                // 如果没有找到路径,回溯,将当前位置从路径中移除
                path.pop();
            }
        }

        return false;
    }

    // 从入口点开始搜索
    dfs(0, 0);
    for (let i of path) console.log(`(${i[0]},${i[1]})`);
})();

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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