-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs_bfs.py
More file actions
60 lines (51 loc) · 1.16 KB
/
dfs_bfs.py
File metadata and controls
60 lines (51 loc) · 1.16 KB
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
## input
#N, M = 4, 5
#matrix = [[0,0,1,1,0],
# [0,0,0,1,1],
# [1,1,1,1,1],
# [0,0,0,0,0]]
'''
def dfs(x,y):
if x < 0 or x >= N or y < 0 or y >= M:
return False
if matrix[x][y] == 0:
matrix[x][y] = 1
dfs(x-1,y)
dfs(x,y-1)
dfs(x+1,y)
dfs(x,y+1)
return True
return False
count = 0
for i in range(N):
for j in range(M):
if dfs(i,j) == True:
count += 1
'''
## answer is 3
#print(count)
from collections import deque
N, M = 5, 6
maze = [[1,0,1,0,1,0],
[1,1,1,1,1,1],
[0,0,0,0,0,1],
[1,1,1,1,1,1],
[1,1,1,1,1,1]]
moves = [[1,0],[-1,0],[0,1],[0,-1]]
def bfs(x,y):
queue = deque()
queue.append((x,y))
while queue:
x, y = queue.popleft()
for move in moves:
nx = x + move[0]
ny = y + move[1]
if nx < 0 or nx >= N or ny < 0 or ny >= M:
continue
if maze[nx][ny] == 0:
continue
if maze[nx][ny] == 1:
maze[nx][ny] = maze[x][y] + 1
queue.append((nx,ny))
return maze[N-1][M-1]
print(bfs(0,0))