Reputation: 1
I want to implement a method that takes the starting and ending locations on a map and returns a path that navigates the map from start to end. (This path must not contain any impassable tiles (Wall tiles) and must be as short as possible.)
So for this implementation, I'm only allowed to use BFS. My first step would be to convert the maze into a graph but I'm not sure how to even start with that. Then I would have to run BFS on the tile containing the maze runner. Lastly, I would have to backtrack from the goal tile to build the path. There's so many steps I feel like I really need some help processing over this.
class GridLocation(val x: Int, val y: Int){
override def toString = s"($x, $y)"
override def equals(that: Any): Boolean = {
that match {
case other: GridLocation =>
this.x == other.x && this.y == other.y
case _ => false
}
}
}
object MapTile {
def generateRow(row: String): List[MapTile] = {
row.map((ch: Char) => MapTile(ch.toString)).toList
}
def apply(tileType: String): MapTile = {
tileType match {
case "-" => new MapTile("ground", true)
case "G" => new MapTile("goal", true)
case "O" => new MapTile("wall", false)
}
}
}
class MapTile(val tileType: String, val passable: Boolean) {
}
def findPath(start: GridLocation, end: GridLocation, map: List[List[MapTile]]): List[GridLocation] = {
//code starts here
}
Upvotes: 0
Views: 490
Reputation: 23
I recommend you to look at A* algorithm, or an other "pathfinding" algorithm. I think that the Youtube Channel "Coding train" had made a video on that.
Good afternoon.
Upvotes: 0
Reputation: 675
Rather than explicitly building a graph, you can just keep the graph implicit by trying, at each cell, to move in each of the four cardinal directions [y+1,x],[y-1,x],[y,x+1],[y,x-1]
and only add the new cell to the queue if it fulfills the following:
To keep track of visited cells, you can use an auxiliary array the size of the grid and mark visited cells off as 1
and unvisited as 0
. Furthermore, to store the path, you can keep another auxiliary array that stores, for each cell, the "parent cell" that led directly to this cell, and upon finishing the BFS you can backtrack parents starting from the end cell all the way back to the start cell.
For clarity, the "parent cell" of cell x
is the cell that was being considered when x
was added to the queue.
Upvotes: 1