-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGraph.py
More file actions
63 lines (48 loc) · 1.15 KB
/
Copy pathGraph.py
File metadata and controls
63 lines (48 loc) · 1.15 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
61
62
63
from Queue import Queue
from Stack import Stack
class Node:
def __init__(self, val, weight = 1, dist = 1):
self.val = val
self.neighbours = []
self.weight = weight
self.dist = dist
class Graph:
def __init__(self, nodes = []):
self.nodes = nodes
def add_node(self, val, weight = 1):
new_node = Node(val, weight)
self.nodes.append(new_node)
def add_edge(self, node_u, node_v):
node_u.neighbours.append(node_v)
def BFS(self):
if len(self.nodes) == 0:
return []
root = self.nodes[0]
visited = set([root])
Q = Queue()
Q.add(root)
BfsResult = []
while Q.size() > 0:
QueueHead = Q.remove()
BfsResult.append(QueueHead)
for neighbour in QueueHead.neighbours:
if neighbour not in visited:
Q.add(neighbour)
visited.add(neighbour)
return BfsResult
def DFS(self):
if len(self.nodes) == 0:
return []
root = self.nodes[0]
visited = set([root])
S = Stack()
S.add(root)
DfsResult = []
while S.size() > 0:
StackTop = S.remove()
DfsResult.append(StackTop)
for neighbour in StackTop.neighbours:
if neighbour not in visited:
S.add(neighbour)
visited.add(neighbour)
return DfsResult