题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
// x:0 - n-1
// y:0 - m-1
let [n, m] = readline().split(' ').map(i => Number(i))
let map = []
for(let i=0; i<n; i++) {
map[i] = readline().split(' ').map(i => Number(i))
}
let res = ['(0,0)'], x0 = 0, y0 = 0, to = [[0, 1], [1, 0], [0, -1], [-1, 0]]
let pass = Array(n).fill(0).map(i => Array(m).fill(0)) // 记录已走位置
fn(x0, y0, res)
res.forEach(p => {
print(p)
})
function fn(x, y, path) {
if(x==n-1 && y==m-1){
// 引用类型的赋值是指针,后续递归可能会修改值,而我们需要的是成功时候的值, 此处深拷贝
res = JSON.parse(JSON.stringify(path))
}
for(let i=0; i<to.length; i++) {
let new_x = x+to[i][0]
let new_y = y+to[i][1]
if(new_x>=0 && new_x<n && new_y>=0 && new_y<m && map[new_x][new_y]==0 && pass[new_x][new_y]==0) {
pass[new_x][new_y] = 1
path.push(`(${new_x},${new_y})`)
fn(new_x, new_y, path)
path.pop() // 回溯
}
}
return
}


