题解 | #迷宫问题#
迷宫问题
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})`); }); })();