HJ43 迷宫问题

题目:
在这里插入图片描述
在这里插入图片描述
分四个方向分别递归,递归结束的条件就是走到最后一个,存储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)
    })
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值