forked from kumaya/python-programs
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphADT.py
More file actions
Latest commit
54 lines (48 loc) · 1.04 KB
/
Copy pathGraphADT.py
File metadata and controls
54 lines (48 loc) · 1.04 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
'''Implement Grpah ADT traversal in python
BFS (Breadth-First-Search) and DFS (Depth-First-Search)
@Inp:
,--->A
| / \
| B C
| |\ /|
| | D |
| | | |
| '-E-'
'----'
'''
# def depth_first_search(graph, start, path=[]):
# '''Recursive dfs from start node'''
# path.append(start)
# for node in graph[start]:
# if not node in path:
# print path
# depth_first_search(graph, node, path)
# return path
defdepth_first_search(graph, start):
'''Iterative dfs from start node'''
path=[]
q= [start]
whileq:
v=q.pop()
ifnotvinpath:
printpath
path.append(v)
q+=graph[v]
returnpath
defbreadth_first_search(graph, start):
'''Iterative bfs from start node'''
path=[]
q= [start]
whileq:
v=q.pop(0)
ifnotvinpath:
printpath
path.append(v)
q+=graph[v]
returnpath
if__name__=="__main__":
graph= {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['D', 'E'], 'D': ['E'], 'E': ['A']}
start='A'
printdepth_first_search(graph, start)
print"*"*80
printbreadth_first_search(graph, start)