From 7cb4fa99bc10bcecde37c1d8af9489f99cc0cc37 Mon Sep 17 00:00:00 2001 From: Karma Riuk Date: Mon, 14 Aug 2023 20:00:41 +0200 Subject: [PATCH] Pulled out the wasVisited function from DFS to genral solver --- solver/dfs.go | 18 +++--------------- solver/solver.go | 30 +++++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 18 deletions(-) diff --git a/solver/dfs.go b/solver/dfs.go index 7df074b..cded04a 100644 --- a/solver/dfs.go +++ b/solver/dfs.go @@ -6,18 +6,14 @@ import ( ) type DFSSolver struct { - visited map[*maze.Node]bool + solver } 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] - 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 = append(stack, current) @@ -53,11 +49,3 @@ func (s *DFSSolver) Solve(m *maze.Maze) *maze.SolvedMaze { } return ret } - -func (s *DFSSolver) wasVisited(node *maze.Node) bool { - if node == nil { - return true - } - visited, _ := s.visited[node] - return visited -} diff --git a/solver/solver.go b/solver/solver.go index 0d34ae6..5901dd7 100644 --- a/solver/solver.go +++ b/solver/solver.go @@ -9,22 +9,46 @@ type Solver interface { Solve(*maze.Maze) *maze.SolvedMaze } +type solver struct { + visited map[*maze.Node]bool +} + type SolverFactory struct { Type *string } const ( - _TURN_LEFT = "turn-left" + _DFS = "dfs" + _BFS = "bfs" ) var TYPES = []string{ - _TURN_LEFT, + _DFS, + _BFS, } func (f *SolverFactory) Get() Solver { switch *f.Type { - case _TURN_LEFT: + case _DFS: return &DFSSolver{} + case _BFS: + return &BFSSolver{} } 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 + } +}