我正在尝试用Haskell实现基于下面链接描述的算法的迷宫解决器。
http://www.cs.bu.edu/teaching/alg/maze/
我是一名新手,对于Haskell和函数式编程都不太熟悉。我正在尝试按照链接中描述的算法进行编码,我已经查阅了许多其他在线资源,但是在迷宫中到达终点后行走没有停止(它会回溯到原点),而且我无法取消标记迷宫中的错误位置。迷宫的样子如下:
.########
.......#.
#.####..#
#.#######
...#.G...
##...####
#..######
我的代码如下所示
findPath :: Int->Int->Maze->(Bool,Maze)
findPath x y maze
| not (isSafe maze x y) = (False,maze)
| isChar maze x y 'G' = trace ("Solution: "++ show maze)(True,maze)
| isChar maze x y '#' = (False,maze)
| isChar maze x y '!' = (False,maze)
| fst walkNorth = (True,markedList)
| fst walkEast = (True,markedList)
| fst walkSouth = (True,markedList)
| fst walkWest = (True,markedList)
| otherwise = (False,unMarkedList)
where markedList = replaceCharInMaze maze x y '+'
unMarkedList = replaceCharInMaze maze x y '!'
walkNorth = findPath x (y-1) markedList
walkEast = findPath (x+1) y markedList
walkSouth = findPath x (y+1) markedList
walkWest = findPath (x-1) y markedList
isSafe函数只是检查边界,isChar函数只是在给定的x,y位置进行字符匹配,replaceCharInMaze函数用提供的字符替换x,y位置处的字符。
isSafe :: [String]->Int->Int->Bool
isSafe list x y
| y >= 0 && y < length (head list) && x >= 0 && x < length list && (isChar list xy '.' || isChar list x y 'G') = True
| otherwise = False
所以,我有两个问题:
- 我无法将未标记的情况持久化到下一个递归调用中,我该如何持久化迷宫的状态,以便未标记的状态也成为解决方案的一部分?
- 随着算法的进行,它走到目标并返回起点,如何阻止这种情况发生?
跟踪语句期间迷宫的输出如下:
+++#..###..#.
.#+++#+++.##.
####+#+#+#-##
...#+++#+#...
.#.####++.##.
.#G+++++#....
.############
....####.....
但它并不止于此,它会追溯到原点并将输出打印出来。
+..#..###..#.
.#...#....##.
####.#.#.#.##
...#...#.#...
.#.####...##.
.#G.....#....
.############
....####.....
walkNorth = findPath' x (y-1) (replaceCharInMaze maze x y '+') walkEast = findPath' (x+1) y (replaceCharInMaze maze x y '+') walkSouth = findPath' x (y+1) (replaceCharInMaze maze x y '+') walkWest = findPath' (x-1) y (replaceCharInMaze (replaceCharInMaze maze x y '!') x y '+')
- Pradeep Samuel Daniel+++#--###--#----# -##+++#+++-##---#-- ####+#+#+---#--#-- +++#+++#+###G+-#-- +#+####++-###+#### +#++++++##---+++++ ################## ++++++++++++++++++
如果不可达,则输出:!--#--###--#----#- ##---#----##---#-- ####-#-#----#--#-- ---#---#-###@--#-- -#-####---######## -#------##-------- -################- ------------------
- Pradeep Samuel Daniel