题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
借别人的思路简化了一下
const [row,col] = readline().split(' ').map(item=>parseInt(item))
// 初始化迷宫数据和有无被探索的数据, 0表示未被探索, -1 表示此方向不通,1 表示已经经过这个位置,防止返回再次遍历
let maze = []
while(temp = readline()){
maze.push(temp.split(' ').map(item=>parseInt(item)))
}
// 设置起点,并标记为已经探索
let currX = 0
let currY = 0
// 存储路径(最终输出的结果)
let line = []
// 定义四个方向,每经过一个点,就要往这四个方向尝试能不能走
const direction = [[1,0],[-1,0],[0,1],[0,-1]]
let finished = false
let ans = []
getRes(0,0)
function getRes(currX, currY){
line.push([currX, currY])
if(currX === row - 1 && currY === col - 1){
finished = true
ans = line.slice()
return
}
if(finished) {
return
}
direction.forEach(([x,y]) => {
const nextX = currX + x
const nextY = currY + y
if(maze[nextX] && maze[nextX][nextY] === 0){
maze[nextX][nextY] = 1
getRes(nextX, nextY)
}
})
line.pop()
}
ans.forEach(([x, y]) => {
console.log(`(${x},${y})`)
})

