-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdfs_solver.py
70 lines (51 loc) · 1.48 KB
/
dfs_solver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import resource
import sys
from numpy.random import shuffle
resource.setrlimit(resource.RLIMIT_STACK, (2 ** 29, -1))
sys.setrecursionlimit(10 ** 6)
found_solution = False
nodes = 0
dist = -1
def dfs(maze, current, end, parent, visited, d):
global found_solution
global nodes
global dist
nodes += 1
if not found_solution:
if current == end:
found_solution = True
dist = d
else:
visited.add(current)
dirs = [(-1, 0), (0, +1), (+1, 0), (0, -1)]
shuffle(dirs)
for dx, dy in dirs:
a, b = current[0] + dx, current[1] + dy
if maze.in_maze(a, b) and not maze.is_wall(a, b) and (a, b) not in visited:
parent[(a, b)] = current
dfs(maze, (a, b), end, parent, visited, d + 1)
def solve_maze(maze, start, end, print_info=False):
assert not maze.is_wall(start[0], start[1])
assert not maze.is_wall(end[0], end[1])
parent = dict()
visited = set()
global found_solution
found_solution = False
global nodes
nodes = 0
global dist
dist = 0
dfs(maze, start, end, parent, visited, 1)
if print_info:
print("Nodes:", nodes)
print("Distance:", dist)
if end not in parent:
return []
else:
path = []
while start != end:
path.append(end)
end = parent[end]
path.append(start)
path.reverse()
return path