2019-05-21 06:06:05 +00:00
|
|
|
|
#!/usr/bin/python
|
2018-10-19 12:48:28 +00:00
|
|
|
|
|
2019-05-21 06:06:05 +00:00
|
|
|
|
# Author: OMKAR PATHAK
|
|
|
|
|
|
|
|
|
|
# We can use Python's dictionary for constructing the graph.
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
2020-01-03 14:25:36 +00:00
|
|
|
|
class AdjacencyList:
|
2019-05-21 06:06:05 +00:00
|
|
|
|
def __init__(self):
|
2020-11-08 15:04:01 +00:00
|
|
|
|
self.adj_list = {}
|
2019-05-21 06:06:05 +00:00
|
|
|
|
|
2020-11-08 15:04:01 +00:00
|
|
|
|
def add_edge(self, from_vertex: int, to_vertex: int) -> None:
|
2019-05-21 06:06:05 +00:00
|
|
|
|
# check if vertex is already present
|
2020-11-08 15:04:01 +00:00
|
|
|
|
if from_vertex in self.adj_list:
|
|
|
|
|
self.adj_list[from_vertex].append(to_vertex)
|
2019-05-21 06:06:05 +00:00
|
|
|
|
else:
|
2020-11-08 15:04:01 +00:00
|
|
|
|
self.adj_list[from_vertex] = [to_vertex]
|
2019-05-21 06:06:05 +00:00
|
|
|
|
|
2020-11-08 15:04:01 +00:00
|
|
|
|
def print_list(self) -> None:
|
|
|
|
|
for i in self.adj_list:
|
|
|
|
|
print((i, "->", " -> ".join([str(j) for j in self.adj_list[i]])))
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
2019-05-21 06:06:05 +00:00
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
if __name__ == "__main__":
|
2019-05-21 06:06:05 +00:00
|
|
|
|
al = AdjacencyList()
|
2020-11-08 15:04:01 +00:00
|
|
|
|
al.add_edge(0, 1)
|
|
|
|
|
al.add_edge(0, 4)
|
|
|
|
|
al.add_edge(4, 1)
|
|
|
|
|
al.add_edge(4, 3)
|
|
|
|
|
al.add_edge(1, 0)
|
|
|
|
|
al.add_edge(1, 4)
|
|
|
|
|
al.add_edge(1, 3)
|
|
|
|
|
al.add_edge(1, 2)
|
|
|
|
|
al.add_edge(2, 3)
|
|
|
|
|
al.add_edge(3, 4)
|
|
|
|
|
|
|
|
|
|
al.print_list()
|
2019-05-21 06:06:05 +00:00
|
|
|
|
|
|
|
|
|
# OUTPUT:
|
|
|
|
|
# 0 -> 1 -> 4
|
|
|
|
|
# 1 -> 0 -> 4 -> 3 -> 2
|
|
|
|
|
# 2 -> 3
|
|
|
|
|
# 3 -> 4
|
|
|
|
|
# 4 -> 1 -> 3
|