Pulled out the wasVisited function from DFS to genral solver

This commit is contained in:
Karma Riuk 2023-08-14 20:00:41 +02:00
parent e53dac17d5
commit 7cb4fa99bc
2 changed files with 30 additions and 18 deletions

View File

@ -6,18 +6,14 @@ import (
) )
type DFSSolver struct { type DFSSolver struct {
visited map[*maze.Node]bool solver
} }
func (s *DFSSolver) Solve(m *maze.Maze) *maze.SolvedMaze { func (s *DFSSolver) Solve(m *maze.Maze) *maze.SolvedMaze {
defer utils.Timer("Turn left algorithm", 2)() defer utils.Timer("DFS algorithm", 2)()
s.initVisited(m)
current, end := m.Nodes[0], m.Nodes[len(m.Nodes)-1] current, end := m.Nodes[0], m.Nodes[len(m.Nodes)-1]
s.visited = make(map[*maze.Node]bool, len(m.Nodes))
for _, node := range m.Nodes {
s.visited[node] = false
}
stack := make([]*maze.Node, 0, len(m.Nodes)) stack := make([]*maze.Node, 0, len(m.Nodes))
stack = append(stack, current) stack = append(stack, current)
@ -53,11 +49,3 @@ func (s *DFSSolver) Solve(m *maze.Maze) *maze.SolvedMaze {
} }
return ret return ret
} }
func (s *DFSSolver) wasVisited(node *maze.Node) bool {
if node == nil {
return true
}
visited, _ := s.visited[node]
return visited
}

View File

@ -9,22 +9,46 @@ type Solver interface {
Solve(*maze.Maze) *maze.SolvedMaze Solve(*maze.Maze) *maze.SolvedMaze
} }
type solver struct {
visited map[*maze.Node]bool
}
type SolverFactory struct { type SolverFactory struct {
Type *string Type *string
} }
const ( const (
_TURN_LEFT = "turn-left" _DFS = "dfs"
_BFS = "bfs"
) )
var TYPES = []string{ var TYPES = []string{
_TURN_LEFT, _DFS,
_BFS,
} }
func (f *SolverFactory) Get() Solver { func (f *SolverFactory) Get() Solver {
switch *f.Type { switch *f.Type {
case _TURN_LEFT: case _DFS:
return &DFSSolver{} return &DFSSolver{}
case _BFS:
return &BFSSolver{}
} }
panic(fmt.Sprintf("Unrecognized solver type %q", *f.Type)) panic(fmt.Sprintf("Unrecognized solver type %q", *f.Type))
} }
func (s *solver) wasVisited(node *maze.Node) bool {
if node == nil {
return true
}
visited, _ := s.visited[node]
return visited
}
func (s *solver) initVisited(m *maze.Maze) {
s.visited = make(map[*maze.Node]bool, len(m.Nodes))
for _, node := range m.Nodes {
s.visited[node] = false
}
}