-
Notifications
You must be signed in to change notification settings - Fork 40
/
route_between_2_vertices.py
59 lines (49 loc) · 1.31 KB
/
route_between_2_vertices.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
#!/usr/bin/python
# Date: 2020-10-20
#
# Description:
# Given a directed graph, design an algorithm to find out whether there is a
# route between 2 nodes.
#
# Approach:
# Starting from source node, use breadth first(BFS) approach to find if we are
# able to find to destination node or not.
#
# Complexity:
# O(V + E) Time
# O(V) Space
import collections
class Graph:
def __init__(self):
self.graph = {}
def add_edge(self, src, dst):
if src in self.graph:
self.graph[src].append(dst)
else:
self.graph[src] = [dst]
def has_path(self, src, dst):
"""Checks if there is a path from source to destination vertex."""
if src == dst:
return True
Q = collections.deque([src])
visited = set()
while Q:
curr = Q.popleft()
visited.add(curr)
for adj in self.graph.get(curr, []):
if adj == dst:
return True
if adj not in visited:
Q.append(adj)
return False
def main():
g = Graph()
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(3, 4)
g.add_edge(2, 1)
assert g.has_path(1, 2) == True
assert g.has_path(1, 4) == True
assert g.has_path(4, 1) == False
if __name__ == '__main__':
main()