AcWing 844. 走迷宫 ( JavaScript )
原题链接
简单
作者:
gaobowen
,
2019-11-30 16:25:26
,
所有人可见
,
阅读 1016
let n = 0, m = 0;//n行,m个整数
let map = [];
let way = [];//保存走过的路径
//上右下左
let dx = [0, 1, 0, -1];
let dy = [-1, 0, 1, 0];
let bfs = () => {
let queue = []; //存放坐标
queue.push([0, 0]);
map[0][0] = 1;//起点需要被标记
let step = 0;
while (queue.length > 0) {
step++;
let k = queue.length;
for (let i = 0; i < k; i++) { //一次取完当前步骤
let top = queue.shift();
for (let j = 0; j < 4; j++) { //寻找4个方向
let x = top[0] + dx[j];
let y = top[1] + dy[j];
if (x >= 0 && x < n && y >= 0 && y < m && map[x][y] === 0) {
map[x][y] = 1;
queue.push([x, y]);
way[x][y] = top;//存放当前步骤的前一步
}
if (x === n - 1 && y === m - 1) {
console.log(step);
//printWay(x,y)
return;
}
}
}
}
}
let printWay = (x, y) => {
let curr = [x, y];
while (curr) {
console.log(curr);
curr = way[curr[0]][curr[1]];
}
}
let buf = '';
process.stdin.on('readable', function () {
let chunk = process.stdin.read();
if (chunk) buf += chunk.toString();
});
let getInputNums = line => line.split(' ').filter(s => s !== '').map(x => parseInt(x));
let getInputStr = line => line.split(' ').filter(s => s !== '');
process.stdin.on('end', function () {
buf.split('\n').forEach(function (line, lineIdx) {
if (lineIdx === 0) {
let a = getInputNums(line);
n = a[0], m = a[1];
} else if (lineIdx <= n) {
map.push(getInputNums(line));
way.push([]);
if(lineIdx === n)
bfs();
}
});
});