【发布时间】:2020-01-16 18:36:02
【问题描述】:
作为一个学校项目,我必须使用递归方法在迷宫中找到解决方案路径,我通常没有解决线性问题的递归算法问题,但是当涉及到多个选择/路径时,我不知道如何只找到一种解决方案。
问题参数:
- 以矩阵表示的迷宫,有多种到达同一终点的方式
- 起点
使用的语言:
- F#
代码输出:
████████████████████
█ █ ██
█ ███ ███ █████ █ ██
█ █ █ █ █ ██
█ █ █ █ █ █ █ ███ ██
█ █Sxxxx █ ██
█ █████ █ █x███ █ ██
█ █ █xxx█ ██
█ █ █ ███████x██████
█ █ █ █ █x ██
█ █ ███ █ █ █x███ ██
█ █ █ █ x█ ██
█ ███ ███ █ █x█ █ ██
█ x█ ██
███ █████████x███ ██
███ █ █xxx█ █ ██
███ █ █ █ █x███ █ ██
███ █ █xxx█ ██
█████████x██████████
█████████E██████████
#:墙
: 路径
E:终点
S:起点
部分代码:
let rec dfs(x,y,path,visited) =
let rec checkVisited point visited =
match visited with
| [] -> false
| (x,y)::xs -> if point = (x,y) then true else checkVisited point xs
let adjacents = [(x,y+1);(x+1,y);(x,y-1);(x-1,y)]
for point in adjacents do
if point = this.endPoint then
this.solutionPath <- path
else
if checkVisited point visited = false && this.checkPoint point && this.isWall point = false then
dfs(fst(point),snd(point),(path@[point]),(visited@[(x,y)]))
这是在迷宫中搜索解决方案的另一种方式(mooore 优化)
let rec dfs(x,y,path) =
// setting the point in the matrix visited (setting it to 'false')
matrix.[y].[x] <- (fst(matrix.[y].[x]),false)
// getting the adjacents of the point
let adjacents = [(x,y+1);(x+1,y);(x,y-1);(x-1,y)]
// iterate the adjacents
for (x1,y1) in adjacents do
// if the adjacent is the end point set the soultion path
if (x1,y1) = this.endPoint then
this.solutionPath <- path
else
// else check if the point is in the matrix and is not yet visited
if this.checkPoint(x1,y1) && snd(matrix.[y1].[x1]) <> false && this.isWall(x1,y1) = false then
// execute recursively the method in the point and add the current poisition to the path
dfs(x1,y1,((x1,y1)::path))
dfs(x,y,[])
我成功了!如果您在执行此操作时遇到任何问题,我会为您提供帮助(即使是其他语言)!
【问题讨论】:
-
基本上,您正在尝试找到能够为您提供到达终点的最短路径的解决方案。因为有多个路径可以到达终点。因此,假设您正在尝试求解到 E 的最短路径。
-
但是您要解决什么问题,例如您只想找出将您带到 E 的任何特定方式,或者您想找到到达 E 的所有可能方式。只是想了解。
-
知道了,这个很简单,我F#不流利,如果我提供逻辑,会有帮助吗?
-
您更擅长哪种语言?
-
返回所有路径也是一种有据可查的方法。解决迷宫的第一项研究;进行有效的尝试;如果您仍然失败,请发布您的结果。你已经有了一个好的开始。
标签: algorithm recursion f# tree maze