-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdepthFirstSearch.py
73 lines (61 loc) · 1.98 KB
/
depthFirstSearch.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class Graph:
def __init__(self, graph_dict=None):
self.graph_dict = graph_dict
def getVertex(self):
return list(self.graph_dict.keys())
def edges(self):
return self.find_edges()
def print_graph(self):
print(self.graph_dict)
def find_edges(self):
edges = []
for vertex in self.graph_dict:
for sibiling in self.graph_dict[vertex]:
if {sibiling, vertex} not in edges:
edges.append({sibiling, vertex})
return edges
def addVertex(self, vertex):
if vertex not in self.graph_dict:
self.graph_dict[vertex] = []
def addEdge(self, edge):
edge = set(edge)
(v1, v2) = tuple(edge)
if v1 in self.graph_dict:
self.graph_dict[v1].append(v2)
else:
self.graph_dict[v1] = v2
if v2 in self.graph_dict:
self.graph_dict[v2].append(v1)
else:
self.graph_dict[v2] = v1
def getNeighbor(self, vertex):
if vertex not in self.graph_dict:
return None
else:
return self.graph_dict[vertex]
def dfs(self, currentVert, visited):
visited[currentVert] = True
print(currentVert),
for neighbor in self.getNeighbor(currentVert):
if neighbor not in visited:
self.dfs(neighbor, visited)
def DFSTraversal(self):
visited = {}
for currentVert in self.graph_dict:
if currentVert not in visited:
self.dfs(currentVert, visited)
graph_elements = {"a": ["c"],
"b": ["c", "e"],
"c": ["a", "b", "d", "e"],
"d": ["c"],
"e": ["c", "b"],
"f": []
}
graph = Graph(graph_elements)
graph.addVertex('g')
graph.addEdge({'f', 'd'})
graph.addEdge({'g', 'f'})
print(graph.getVertex())
print(graph.edges())
print('\nFollowing is Depth First Traversal:')
graph.DFSTraversal()