-
Notifications
You must be signed in to change notification settings - Fork 13
/
Graph.py
56 lines (44 loc) · 1.49 KB
/
Graph.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
class Graph:
def __init__(self, gdict = None):
if gdict is None:
gdict = {}
self.gdict = gdict
def addEdge(self, vertex, edge):
self.gdict[vertex].append(edge)
def bfs(self, vertex): # time - O(V+E) , V = vertex, E = edges, space - O(V+E)
#create list to keep track of visited nodes
visited = [vertex]
#queue initialized with the vertex
queue = [vertex]
while queue:
deqVertex = queue.pop(0)
print(deqVertex)
for adjVertex in self.gdict[deqVertex]:
if adjVertex not in visited:
visited.append(adjVertex)
queue.append(adjVertex)
def dfs(self, vertex): # time - O(V+E) , V = vertex, E = edges, space - O(V+E)
visited = [vertex]
stack = [vertex]
while stack:
popVertex = stack.pop()
print(popVertex)
for adjVertex in self.gdict[popVertex]:
if adjVertex not in visited:
visited.append(adjVertex)
stack.append(adjVertex)
#create graph by declaring dictionary
customDict = {
"a" : ["b","c"],
"b" : ["a","d","e"],
"c" : ["a","e"],
"d" : ["b","e","f"],
"e" : ["d","f"],
"f" : ["d","e"]
}
graph = Graph(customDict)
#graph.addEdge("d", "e")
print(graph.gdict)
graph.bfs("a")
print("------------")
graph.dfs("a")