-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph1.py
52 lines (40 loc) · 1003 Bytes
/
graph1.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
class node:
def __init__(self, val):
self.data = val
self.list = {} # node index : wt
class graph:
def __init__(self):
self.nodes = []
def addNodes(self, values):
for val in values:
self.nodes.append(node(val))
def addEdges(self, node, edges):
for edge in edges:
self.nodes[node].list[edge] = 1
self.nodes[edge].list[node] = 1
def dfs(self, idx, covered=[]):
print(idx, self.nodes[idx].data)
covered.append(idx)
for n in self.nodes[idx].list:
if n not in covered:
self.dfs(n, covered)
def bfs(self, idx):
queue = [idx]
covered = [idx]
while queue:
n = queue.pop(0)
print(n, self.nodes[n].data)
#covered.append(n)
for x in self.nodes[n].list:
if x not in covered:
queue.append(x)
covered.append(x)
g = graph()
g.addNodes([2, 5, 9, 12, 32, 42, 13, 23])
g.addEdges(0, [1, 3, 5])
g.addEdges(1, [2, 4, 6])
g.addEdges(2, [3, 5, 7])
g.addEdges(3, [4, 6, 3])
g.dfs(0)
print()
g.bfs(0)