As a school project I have to find the solution path in a maze using the backtracking method recursively, I usually have no problem solving algorithms with recursion, on linear problems, however when it comes of having multiple choices/paths to follow I don't know how to find only 1 solution.
Problem parameters:
- A maze represented in a matrix which has multiple ways of getting to the same end point
- The starting point
Language used:
- F#
Output of the code:
████████████████████
█ █ ██
█ ███ ███ █████ █ ██
█ █ █ █ █ ██
█ █ █ █ █ █ █ ███ ██
█ █Sxxxx █ ██
█ █████ █ █x███ █ ██
█ █ █xxx█ ██
█ █ █ ███████x██████
█ █ █ █ █x ██
█ █ ███ █ █ █x███ ██
█ █ █ █ x█ ██
█ ███ ███ █ █x█ █ ██
█ x█ ██
███ █████████x███ ██
███ █ █xxx█ █ ██
███ █ █ █ █x███ █ ██
███ █ █xxx█ ██
█████████x██████████
█████████E██████████
#: Walls
: Paths
E: End Point
S: Start Point
Portion of the code:
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)]))
This is another way (mooore optimized) of searching the solution in a maze
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,[])
I have made it! if you have any troubles doing this i will help you (even in other languages)!