-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.py
41 lines (32 loc) · 1.03 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
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def breadth_first_search(self, start):
visited = {}
visited[start] = True
queue = []
queue.append(start)
while queue:
current = queue.pop(0)
neighbours = self.graph[current]
for neighbour in neighbours:
if visited.get(neighbour):
continue
queue.append(neighbour)
visited[neighbour] = True
def depth_first_search(self, start):
visited = {}
visited[start] = True
stack = []
stack.append(start)
while stack:
current = stack.pop()
neighbours = self.graph[current]
for neighbour in neighbours:
if visited.get(neighbour):
continue
stack.append(neighbour)
visited[neighbour] = True