2023-08-10 19:39:16 +02:00
|
|
|
package solver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"maze-solver/maze"
|
|
|
|
"maze-solver/utils"
|
|
|
|
)
|
|
|
|
|
2023-08-17 13:37:54 +02:00
|
|
|
type DFSSolver struct {
|
|
|
|
solved_chan chan<- *maze.SolvedMaze
|
|
|
|
}
|
2023-08-10 19:39:16 +02:00
|
|
|
|
2023-08-13 21:31:47 +02:00
|
|
|
func (s *DFSSolver) Solve(m *maze.Maze) *maze.SolvedMaze {
|
2023-08-14 20:00:41 +02:00
|
|
|
defer utils.Timer("DFS algorithm", 2)()
|
2023-08-10 19:39:16 +02:00
|
|
|
|
|
|
|
current, end := m.Nodes[0], m.Nodes[len(m.Nodes)-1]
|
|
|
|
|
|
|
|
stack := make([]*maze.Node, 0, len(m.Nodes))
|
|
|
|
stack = append(stack, current)
|
|
|
|
|
|
|
|
for current != end {
|
2023-08-15 15:41:24 +02:00
|
|
|
current.Visited = true
|
2023-08-17 13:37:54 +02:00
|
|
|
if s.solved_chan != nil {
|
|
|
|
s.solved_chan <- &maze.SolvedMaze{
|
|
|
|
Maze: m,
|
|
|
|
Solution: stack,
|
|
|
|
}
|
|
|
|
}
|
2023-08-10 19:39:16 +02:00
|
|
|
|
2023-08-15 15:42:53 +02:00
|
|
|
left_visited, right_visited, up_visited, down_visited := visited(current.Left), visited(current.Right), visited(current.Up), visited(current.Down)
|
2023-08-10 19:39:16 +02:00
|
|
|
|
|
|
|
if left_visited && right_visited && up_visited && down_visited {
|
|
|
|
// dead end or no more visited nodes
|
|
|
|
stack = stack[:len(stack)-1]
|
|
|
|
current = stack[len(stack)-1]
|
|
|
|
} else {
|
|
|
|
|
|
|
|
if !left_visited {
|
|
|
|
current = current.Left
|
|
|
|
} else if !down_visited {
|
|
|
|
current = current.Down
|
|
|
|
} else if !right_visited {
|
|
|
|
current = current.Right
|
|
|
|
} else if !up_visited {
|
|
|
|
current = current.Up
|
|
|
|
}
|
|
|
|
|
|
|
|
stack = append(stack, current)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
ret := &maze.SolvedMaze{
|
|
|
|
Maze: m,
|
|
|
|
Solution: stack,
|
|
|
|
}
|
|
|
|
return ret
|
|
|
|
}
|