题解 | #迷宫问题#

迷宫问题

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
}
全部评论

相关推荐

11-07 16:07
深圳大学 运营
前端飞升:学长,阿里不是卡双非吗,我深也能去吗
点赞 评论 收藏
分享
不知道怎么取名字_:两个方向 1.简历针对性准备下 2.面试前也需要准备的 主要还是要看各个公司需求,看公司行业和岗位描述,那里面已经写了对技术的需求,一份简历,不可能和所有嵌入式岗位都匹配的
投递北京经纬恒润科技股份有限公司等公司6个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务