Java – what kind of maze solving algorithm is this?
I tried to find out if this algorithm was a * (A-star) algorithm or something, but I was still confused
Stack<Cell> stack = new Stack<>(); stack.push(maze.start()); stack.peek().mark(SOLUTION_MARK); while (!stack.peek().hasMark(Cell.END)) { Cell current = stack.peek(); ArrayList<Cell> dirs = current.neighbors(); boolean found = false; for (Cell next : dirs) { if (next.hasMark(ERROR_MARK) || next.hasMark(SOLUTION_MARK)) { continue; } stack.push(next); next.mark(SOLUTION_MARK); found = true; break; } if (!found) { stack.pop().mark(ERROR_MARK); } for (MazeBody listener : listeners) { listener.repaint(); } }
Mark. java
public final class Mark { private static Map<String,Mark> TABLE = new HashMap<>(); private String name; private Mark(String markName) { name = markName; } public static Mark get(String name) { Mark mark = TABLE.get(name); if (mark == null) { mark = new Mark(name); TABLE.put(name,mark); } return mark; } }
Solution
This is written in depth first search iterations rather than recursion
Recursive DFS (advance order) pseudo code is as follows:
visit (current node) for each child node of current node if node is not explored dfs (node)
The iterative versions of DFS are as follows:
Put current node on stack In a while loop pop the stack if not empty visit (popped node) push all Unvisited and NotVisiting neighbors of popped node on the stack End while
Invisible and notvisiting in the iterative version mean that the node has neither been accessed nor the stack has been accessed
The time complexity of the algorithm depends on whether the graph has been stored as adjacency list or adjacency matrix For a list, it is O (n) For a matrix, it becomes o (N2), because even if you explore each node only once, you must access each row and column of the matrix to see if there is a path between node X and node y
The spatial complexity of the algorithm can reach the worst value of O (n). This happens when the graph makes each node have only one neighbor, which becomes like a single linked list