-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFS_SlimeMoldAlgorithm.py
55 lines (42 loc) · 1.63 KB
/
DFS_SlimeMoldAlgorithm.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
import random
# Define the maze
maze = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 2, 1],
[1, 0, 1, 1, 1, 1, 1, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1, 0, 1, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 1, 1],
[1, 0, 1, 0, 1, 1, 1, 0, 1, 1],
[1, 0, 1, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
start = (1, 1)
end = (1, 8)
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # right, down, left, up
def slime_mold_path(maze, start, end):
visited = set()
stack = [(start, [start])]
while stack:
position, path = stack.pop()
# If the current position is the end, return the path
if position == end:
return path
# Otherwise, spread out to neighboring cells
for d in directions:
new_position = (position[0] + d[0], position[1] + d[1])
if (0 <= new_position[0] < len(maze) and
0 <= new_position[1] < len(maze[0]) and
maze[new_position[0]][new_position[1]] in [0, 2] and
new_position not in visited):
# Retract from dead ends
if new_position not in path:
new_path = path + [new_position]
stack.append((new_position, new_path))
visited.add(new_position)
# If we've reached the end, stop spreading in this direction
if new_position == end:
return new_path
return None
print(slime_mold_path(maze, start, end))