Implement weighted and unweighted directed graph data structure in Python.

Directed Graph

In an adjacency list representation of the graph, each vertex in the graph stores a list of neighboring vertices. Following is the pictorial representation for the corresponding adjacency list for the above graph:

 
Adjacency List

1. Directed Graph Implementation

Following is the Python implementation of a directed graph using an adjacency list:

Download  Run Code

Output:

(0 —> 1)
(1 —> 2)
(2 —> 0) (2 —> 1)
(3 —> 2)
(4 —> 5)
(5 —> 4)

2. Weighted Directed Graph Implementation

In a weighted graph, every edge has a weight or cost associated with it.

Weighted Directed Graph

Following is the Python implementation of a weighted directed graph using an adjacency list. The implementation is similar to the above implementation, except the weight is now stored in the adjacency list with every edge.

Download  Run Code

Output:

(0 —> 1, 6)
(1 —> 2, 7)
(2 —> 0, 5) (2 —> 1, 4)
(3 —> 2, 10)
(4 —> 5, 1)
(5 —> 4, 3)

 
Also see:

Implement Graph Data Structure in C

Graph Implementation in C++ using STL

Graph Implementation in Java using Collections