-
Notifications
You must be signed in to change notification settings - Fork 43
/
dfs.py
62 lines (55 loc) · 1.1 KB
/
dfs.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
#---------------------------------------------------------------
# DFS
#---------------------------------------------------------------
# BFS VS DFS
# https://cuijiahua.com/blog/2018/01/alogrithm_10.html
# V0 : DEV
# V1
# DFS in recursion version
# https://www.jianshu.com/p/66508acedd79
def dfs_recursion(G,s,S=None,res=None):
if S is None:
# save visited nodes
S=set()
if res is None:
res=[]
res.append(s)
S.add(s)
for u in G[s]:
if u in S:
continue
S.add(u)
dfs_recursion(G,u,S,res)
return res
# G={
# 'a':{'b','f'},
# 'b':{'c','d','f'},
# 'c':{'d'},
# 'd':{'e','f'},
# 'e':{'f'},
# 'f':{}
# }
# res=dfs(G,'a')
# print(res)
# DFS in Iteration verison
def dfs_iteration(G,s):
Q=[]
S=set()
Q.append(s)
while Q:
u=Q.pop()
if u in S:
continue
S.add(u)
Q.extend(G[u])
yield u
# G={
# 'a':{'b','f'},
# 'b':{'c','d','f'},
# 'c':{'d'},
# 'd':{'e','f'},
# 'e':{'f'},
# 'f':{}
# }
# res=list(dfs(G,'a'))
# print(res)