forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maze_search.py
67 lines (46 loc) · 1.45 KB
/
maze_search.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
from collections import deque
'''
BFS time complexity : O(|E| + |V|)
BFS space complexity : O(|E| + |V|)
do BFS from (0,0) of the grid and get the minimum number of steps needed to get to the lower right column
only step on the columns whose value is 1
if there is no path, it returns -1
Ex 1)
If grid is
[[1,0,1,1,1,1],
[1,0,1,0,1,0],
[1,0,1,0,1,1],
[1,1,1,0,1,1]],
the answer is: 14
Ex 2)
If grid is
[[1,0,0],
[0,1,1],
[0,1,1]],
the answer is: -1
'''
def maze_search(maze):
BLOCKED, ALLOWED = 0, 1
UNVISITED, VISITED = 0, 1
initial_x, initial_y = 0, 0
if maze[initial_x][initial_y] == BLOCKED:
return -1
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
height, width = len(maze), len(maze[0])
target_x, target_y = height - 1, width - 1
queue = deque([(initial_x, initial_y, 0)])
is_visited = [[UNVISITED for w in range(width)] for h in range(height)]
is_visited[initial_x][initial_y] = VISITED
while queue:
x, y, steps = queue.popleft()
if x == target_x and y == target_y:
return steps
for dx, dy in directions:
new_x = x + dx
new_y = y + dy
if not (0 <= new_x < height and 0 <= new_y < width):
continue
if maze[new_x][new_y] == ALLOWED and is_visited[new_x][new_y] == UNVISITED:
queue.append((new_x, new_y, steps + 1))
is_visited[new_x][new_y] = VISITED
return -1