const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let n = 0, m = 0
let maze = [] //迷宫路径
let dis = [] //迷宫路径距离
let path = [] //寻路路径
let directions = [[0, -1], [0, 1], [-1, 0], [1, 0]] //上下左右
let inputCount = 0
rl.on('line', line => {
if (inputCount == 0){
let input = line.split(' ')
n = Number(input[0])
m = Number(input[1])
inputCount++
}else{
maze.push(line.split(' ').map(n => {return Number(n)}))
}
})
rl.on('close', line => {
// 初始化每一格距离为-1,则表示没走过
dis = maze.map(n => {return n.map(() => {return -1})})
// 初始化路径起点位置和距离
path[0] = [0,0]
dis[0][0] = 0
while(path.length > 0){
// 推出队头
let tmp = path.shift()
//遍历上下左右,找tmp的下一个可走的方向
directions.map((direction) => {
let nextX = tmp[0]+direction[0], nextY = tmp[1]+direction[1]
if(nextX >= 0 && nextY >= 0 && nextX < n && nextY < m){
if(maze[nextX][nextY] == 0 && dis[nextX][nextY] == -1){
dis[nextX][nextY] = dis[tmp[0]][tmp[1]] + 1
path.push([nextX, nextY])
}
}
})
}
console.log(dis[n-1][m-1])
})
输出路径
let i = n-1, j = m-1
let res = [[i, j]]
while(i>0 && j>0){
let pre = directions.map((direction) => {
let preX = i+direction[0], preY = j+direction[1]
if(preX >= 0 && preY >= 0 && preX < n && preY < m){
if(dis[i][j] == dis[preX][preY] + 1 && dis[preX][preY] != -1){
i = preX, j = preY
res.push([i, j])
}
}
})
}
console.log(res)