题解 | #走迷宫#
走迷宫
https://www.nowcoder.com/practice/e88b41dc6e764b2893bc4221777ffe64
求助,为什么栽在最后一题
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 arr = []; let [height, width] = (await readline()).split(" "); let [x1, y1, x2, y2] = (await readline()).split(" "); while ((line = await readline())) { arr.push(line); } let cur = [x1 - 1, y1 - 1]; let pre = [x2 - 1, y2 - 1]; let arr2 = Array.from({ length: height }, () => { return Array.from({ length: width }, () => 0); }); const queue = []; const visited = new Set(); let bool = false; const bfs = () => { while (queue.length && !bool) { const [x, y] = queue.shift(); [ [x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1], ].forEach((item) => { const [itemX, itemY] = item; if ( !visited.has(item.join("")) && arr[itemX]?.[itemY] === "." ) { queue.push(item); visited.add(item.join("")); arr2[itemX][itemY] = [x, y]; if (item.join("") === pre.join("")) bool = true; } }); } }; let stack = []; const fromTo = (from, to) => { if (arr[to[0]][to[1]] === "*") { return; } else { visited.add(from.join("")); queue.push(from); bfs(); let [x, y] = to; while (arr2[x][y]) { stack.push(`${x}${y}`); [x, y] = arr2[x][y]; } } }; fromTo(cur, pre); console.log(stack.length ? stack.length : -1); })();