题目:
分四个方向分别递归,递归结束的条件就是走到最后一个,存储min(当前路径,已存路径)
提交:
while ((line = readline())) {
const arr = line.split(' ').map(item => Number(item))
const rowNum = arr[0]
const columnNum = arr[1]
const maze = []
for (let i = 0; i < rowNum; i++) {
maze[i] = readline().split(' ').map(item => Number(item))
}
let shortestPath = []
let tempPath = []
function getShortestPath(x, y, count) {
maze[x][y] = 1
// 用于递归前缓存当前路径,不论递归结果如何按之前的路径继续走下去
let currentTempPath = [...tempPath]
if (x === rowNum - 1 && y === columnNum - 1) {
tempPath.push('(' + x + ',' + y + ')')
if (!shortestPath.length || count < shortestPath.length) {
shortestPath = [...tempPath]
return
}
}
if (x - 1 >= 0 && maze[x - 1][y] !== 1) {
tempPath.push('(' + x + ',' + y + ')')
getShortestPath(x - 1, y, count + 1)
tempPath = [...currentTempPath]
}
if (x + 1 < rowNum && maze[x + 1][y] !== 1) {
tempPath.push('(' + x + ',' + y + ')')
getShortestPath(x + 1, y, count + 1)
tempPath = [...currentTempPath]
}
if (y - 1 >= 0 && maze[x][y - 1] !== 1) {
tempPath.push('(' + x + ',' + y + ')')
getShortestPath(x, y - 1, count + 1)
tempPath = [...currentTempPath]
}
if (y + 1 < columnNum && maze[x][y + 1] !== 1) {
tempPath.push('(' + x + ',' + y + ')')
getShortestPath(x, y + 1, count + 1)
tempPath = [...currentTempPath]
}
maze[x][y] = 0
}
getShortestPath(0, 0, 1)
shortestPath.forEach(item => {
console.log(item)
})
}