VOOZH about

URL: https://www.geeksforgeeks.org/python/building-an-undirected-graph-and-finding-shortest-path-using-dictionaries-in-python/

⇱ Building an undirected graph and finding shortest path using Dictionaries in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Building an undirected graph and finding shortest path using Dictionaries in Python

Last Updated : 15 Jul, 2025

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. 

Building a Graph using Dictionaries

👁 Image

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:  


Output: 
{
 'G': ['C'], 
 'F': ['C'], 
 'E': ['A', 'B', 'D'], 
 'A': ['B', 'E', 'C'], 
 'B': ['A', 'D', 'E'], 
 'D': ['B', 'E'], 
 'C': ['A', 'F', 'G']
}

 

Shortest Path between two nodes of graph

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:


Output: 
Shortest path = A B D

 
Comment