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 are stored. For example, consider the following adjacency list corresponding to the sample graph shown previously:

The numbers in the box represent the vertices. The 0 index represents the A vertex of the graph, with its adjacent nodes being B and C. The 1 index represents the B vertex of the graph, with its adjacent nodes of E, C, and A. Similarly, the other vertices, C, E, and F, of the graph are represented at the indices of 2, 3, and 4 with their adjacent nodes, as shown in the previous diagram

Using a list for the representation is quite restrictive, because we lack the ability to directly use the vertex labels. Therefore, a dictionary data structure is more suitable to represent the graph. To implement the same preceding graph using a dictionary data structure, we can use the following statements:

    graph = dict() 
graph['A'] = ['B', 'C']
graph['B'] = ['E','C', 'A']
graph['C'] = ['A', 'B', 'E','F']
graph['E'] = ['B', 'C']
graph['F'] = ['C']

Now we can easily establish that the A vertex has the adjacent vertices of B and C. The F vertex has the C vertex as its only neighbor. Similarly, the B vertex has adjacent vertices of E, B, and A.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset