首页 > 解决方案 > 迷宫求解器跳过块 Javasript

问题描述

我正在尝试制作迷宫求解器,但有时会跳过块。该代码从二维数组中解出一个迷宫。我认为每次回溯发生时都会发生跳过。在代码b中是一堵墙,p是一个已经访问过的块。

function solveMaze(maze, start, end){
    let here = start,
    path = [here]
    maze[here.y][here.x] = 'p'

    while(!(path[path.length-1].x == end.x && path[path.length-1].y == end.y)){
        let options = [{x: here.x + 1, y: here.y}, {x: here.x - 1, y: here.y}, {x: here.x, y: here.y + 1}, {x: here.x, y: here.y - 1}]
        let moves = []

        for(let i = 0; i < options.length; i++){
            if(typeof maze[options[i].y] !== 'undefined' && typeof maze[options[i].y][options[i].x] !== 'undefined' && maze[options[i].y][options[i].x] != 'b' && maze[options[i].y][options[i].x] != 'p'){
                moves.push(options[i])
            }
        }
        if(moves.length){
            let next = moves[Math.floor(Math.random()*moves.length)]

            maze[next.y][next.x] = 'p'

            path.push(here = next)
        }
        else{
            here = path.pop()
        }
    }
    return path
}

小提琴

标签: javascriptcanvasmaze

解决方案


看起来问题出在您备份并尝试另一条路径时。所以把当前点放回路径堆栈上。

这个:

   maze[next.y][next.x] = 'p'

   path.push(here = next)

变成:

   maze[next.y][next.x] = 'p'
   path.push(here)  // put the current location back on there
   path.push(here = next)

位置将被添加到路径中太多次,因此如果您使用路径来计数,那么它不会准确,但对于绘制红色路径,这是一个不错的技巧。

顺便说一句,如果您只需要唯一性,您可以使用Set或尝试更改您的推送/弹出逻辑。


推荐阅读