我想用scala解决迷宫问题,使用回溯。用回溯解决迷宫
我的问题是,我一直在得到StackOverflow错误。
我已经尝试了很多事情,但我总是以StackOverflow结束。
findStart()和getWay()显示了我用过的两种方法。
我知道可以用Streams做到这一点,并在一次递归中计算所有可能的方式,但我想先用回溯来解决它。
这里是我的代码:
object MazeSolver {
case class Cell(free: Boolean, start: Boolean)
type Maze = Seq[Seq[Cell]]
def main(args: Array[String]) = {
val lab = lislab("laby1.rinth")
val entrance = findStart(lab, Position(0, 0))
println(getWay(lab, entrance(0), entrance(0), Nil))
}
def findStart(lab: Maze, pos: Position): List[Position] = {
try {
if (lab(pos.column)(pos.row).start)
List(pos)
else
findStart(lab, pos.south) ::: findStart(lab, pos.north) ::: findStart(lab, pos.west) ::: findStart(lab, pos.east)
} catch {
case _: java.lang.IndexOutOfBoundsException => Nil
}
}
def getWay(maze: Maze, pos: Position, lastPos: Position, way: List[Position]): List[Position] = {
try {
if (!maze(pos.column)(pos.row).free && !maze(pos.column)(pos.row).start) {
Nil
} else {
if (isExit(pos, maze)) {
pos :: way
} else {
val posList = List(pos.north, pos.south, pos.west, pos.east)
posList.foreach { x =>
val tail = getWay(maze, x, pos, way)
if(tail != Nil) tail :: way
}
Nil
}
}
} catch { case _: java.lang.IndexOutOfBoundsException => way }
}
def lislab(fn: String): Maze = {
try {
(for (column <- io.Source.fromFile(fn, "UTF-8").getLines.toList)
yield for (c <- column) yield Cell(c == ' ', c == '?')).toIndexedSeq
} catch { case _: java.io.FileNotFoundException => Nil }
}
case class Position(column: Int, row: Int) {
override def toString = "(" + column + "." + row + ")"
def north = Position(column - 1, row)
def south = Position(column + 1, row)
def west = Position(column, row - 1)
def east = Position(column, row + 1)
}
def isExit(pos: Position, lab: Maze): Boolean = {
val cell = lab(pos.column)(pos.row)
cell.free && (pos.column == 0
|| pos.column == lab.length - 1
|| pos.row == 0
|| pos.row == lab(0).length - 1)
}
}
我在做什么错?我如何使findStart()和getWay()函数正常工作?
的findStart是找到一个迷宫的入口。它将被标记为?所以不应该有一个检查,如果领域是免费的我猜。如果我像这样过滤: 'filter(x =>!visited.contains(x)&& indexInBound(maze,x))'我仍然以infinte递归结束。 –
我现在刚刚使用这个方法来寻找开始:'def findStart2(maze:Maze,position:Position):Position = {{迷宫(a).length){(迷宫(a)(b))。开始)返回位置(a,b) } } 位置(-1,-1) } 使用getway()函数的答案帮助我解决了这个问题。谢谢一堆 –