forked from kumaya/python-programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphADT.py
54 lines (48 loc) · 1.04 KB
/
GraphADT.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
'''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
def depth_first_search(graph, start):
'''Iterative dfs from start node'''
path=[]
q = [start]
while q:
v = q.pop()
if not v in path:
print path
path.append(v)
q += graph[v]
return path
def breadth_first_search(graph, start):
'''Iterative bfs from start node'''
path=[]
q = [start]
while q:
v = q.pop(0)
if not v in path:
print path
path.append(v)
q += graph[v]
return path
if __name__ == "__main__":
graph = {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['D', 'E'], 'D': ['E'], 'E': ['A']}
start = 'A'
print depth_first_search(graph, start)
print "*"*80
print breadth_first_search(graph, start)