javascript - 迷宫求解器跳过块 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
}
解决方案
看起来问题出在您备份并尝试另一条路径时。所以把当前点放回路径堆栈上。
这个:
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或尝试更改您的推送/弹出逻辑。
推荐阅读
- javascript - 将数据从 .json 文件导入到 Brain.js 神经网络
- javascript - 实现复杂的 TreeList 结构
- angular - 动态改变提供者的价值
- mysql - 如何从 django 的前端在表中添加一列
- java - 如何使用 JPA 中的规范连接多个列?
- scala - 如何使用 Apache Spark 和 Scala 创建嵌套 json
- android - 在 gradle 中添加 appcompat-v7 不会自动将我的布局视图切换到 AppCompat 版本
- events - 如何在 servicenow 的日历中查看事件“我的日程安排”
- c++ - 访问旧堆栈帧
- c# - 如何在 Visual Basic 中从 C# 转换对象