Graphs can be represented with two main forms while implementing them in Python. One way is to use an adjacency list, and the other is to use an adjacency matrix. Let's consider an example, shown in the following diagram, to develop both types of representation for graphs:
Graph representations
Adjacency lists
An adjacency list stores all the nodes, along with other nodes that are directly connected to them in the graph. Two nodes, A and B, in a graph G, are said to be adjacent if there is a direct connection between them. A list data structure in Python is used to represent a graph. The indices of the list can be used to represent the nodes or vertices in the graph.
At each index, the adjacent nodes to that vertex...