Skip to content

Commit 1d3e869

Browse files
committedJun 27, 2017
Graph implementation in Python using Adjacency List
1 parent bcf6d13 commit 1d3e869

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
 

‎Graph/Graph.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Author: OMKAR PATHAK
2+
3+
# We can use Python's dictionary for constructing the graph
4+
5+
class AdjacencyList(object):
6+
def __init__(self):
7+
self.List = {}
8+
9+
def addEdge(self, fromVertex, toVertex):
10+
# check if vertex is already present
11+
if fromVertex in self.List.keys():
12+
self.List[fromVertex].append(toVertex)
13+
else:
14+
self.List[fromVertex] = [toVertex]
15+
16+
def printList(self):
17+
for i in self.List:
18+
print(i,'->',' -> '.join([str(j) for j in self.List[i]]))
19+
20+
if __name__ == '__main__':
21+
al = AdjacencyList()
22+
al.addEdge(0, 1)
23+
al.addEdge(0, 4)
24+
al.addEdge(4, 1)
25+
al.addEdge(4, 3)
26+
al.addEdge(1, 0)
27+
al.addEdge(1, 4)
28+
al.addEdge(1, 3)
29+
al.addEdge(1, 2)
30+
al.addEdge(2, 3)
31+
al.addEdge(3, 4)
32+
33+
al.printList()
34+
35+
# OUTPUT:
36+
# 0 -> 1 -> 4
37+
# 1 -> 0 -> 4 -> 3 -> 2
38+
# 2 -> 3
39+
# 3 -> 4
40+
# 4 -> 1 -> 3

0 commit comments

Comments
 (0)
Please sign in to comment.