Skip to content

Commit db823c4

Browse files
committed
added graph
1 parent d7f2efd commit db823c4

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

datastructures/directed_graph.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
from collections import defaultdict
2+
3+
class Graph:
4+
def __init__(self):
5+
self.graph = defaultdict(list)
6+
7+
def __str__(self):
8+
return str(self.graph)
9+
10+
def add_edge(self, start, end):
11+
self.graph[start].append(end)
12+
self.graph[end].append(start)
13+
self.graph[end].remove(start)
14+
15+
def _dps(self, start, visited):
16+
visited[start] = True
17+
print(start)
18+
19+
for vertice in self.graph[start]:
20+
if not visited[vertice]:
21+
self._dps(vertice, visited)
22+
23+
def depth_search(self, start):
24+
visited = {key: False for key, _ in self.graph.items()}
25+
print(self.graph)
26+
self._dps(start, visited)
27+
28+
def wide_search(self, start):
29+
visited = {key: False for key, _ in self.graph.items()}
30+
queue = [start]
31+
print(self.graph)
32+
33+
while queue:
34+
start = queue.pop(0)
35+
visited[start] = True
36+
print(start)
37+
38+
for vertice in self.graph[start]:
39+
if not visited[vertice]:
40+
queue.append(vertice)
41+
visited[vertice] = True
42+
43+
44+

0 commit comments

Comments
 (0)