![]() |
VOOZH | about |
Prerequisites:
In this article, we will be looking at how to build an undirected graph and then find the shortest path between two nodes/vertex of that graph easily using dictionaries in Python Language.
Approach: The idea is to store the adjacency list into the dictionaries, which helps to store the graph in any format not only in the form of the integers. Here we have used characters as a reference on those places any custom objects can also be used.
Below is the implementation of the above approach:
{
'G': ['C'],
'F': ['C'],
'E': ['A', 'B', 'D'],
'A': ['B', 'E', 'C'],
'B': ['A', 'D', 'E'],
'D': ['B', 'E'],
'C': ['A', 'F', 'G']
}Approach: The idea is to use queue and visit every adjacent node of the starting nodes that traverses the graph in Breadth-First Search manner to find the shortest path between two nodes of the graph.
Below is the implementation of the above approach:
Shortest path = A B D