Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Building an undirected graph and finding shortest path using Dictionaries in Python
Next article icon

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

Last Updated : 15 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisites: 

  • BFS for a Graph
  • Dictionaries in Python

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

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:  

Python3
# Python3 implementation to build a  # graph using Dictionaries  from collections import defaultdict  # Function to build the graph def build_graph():     edges = [         ["A", "B"], ["A", "E"],          ["A", "C"], ["B", "D"],         ["B", "E"], ["C", "F"],         ["C", "G"], ["D", "E"]     ]     graph = defaultdict(list)          # Loop to iterate over every      # edge of the graph     for edge in edges:         a, b = edge[0], edge[1]                  # Creating the graph          # as adjacency list         graph[a].append(b)         graph[b].append(a)     return graph  if __name__ == "__main__":     graph = build_graph()          print(graph) 

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:

Python3
# Python implementation to find the  # shortest path in the graph using  # dictionaries   # Function to find the shortest # path between two nodes of a graph def BFS_SP(graph, start, goal):     explored = []          # Queue for traversing the      # graph in the BFS     queue = [[start]]          # If the desired node is      # reached     if start == goal:         print("Same Node")         return          # Loop to traverse the graph      # with the help of the queue     while queue:         path = queue.pop(0)         node = path[-1]                  # Condition to check if the         # current node is not visited         if node not in explored:             neighbours = graph[node]                          # Loop to iterate over the              # neighbours of the node             for neighbour in neighbours:                 new_path = list(path)                 new_path.append(neighbour)                 queue.append(new_path)                                  # Condition to check if the                  # neighbour node is the goal                 if neighbour == goal:                     print("Shortest path = ", *new_path)                     return             explored.append(node)      # Condition when the nodes      # are not connected     print("So sorry, but a connecting"\                 "path doesn't exist :(")     return  # Driver Code if __name__ == "__main__":          # Graph using dictionaries     graph = {'A': ['B', 'E', 'C'],             'B': ['A', 'D', 'E'],             'C': ['A', 'F', 'G'],             'D': ['B', 'E'],             'E': ['A', 'B', 'D'],             'F': ['C'],             'G': ['C']}          # Function Call     BFS_SP(graph, 'A', 'D') 

Output: 
Shortest path =  A B D

 

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

M

murtuza_chawala
Improve
Article Tags :
  • Graph
  • Algorithms
  • Python
  • Data Structures
  • DSA
  • Algorithms-Graph Shortest Paths Quiz
  • python-dict
  • Python dictionary-programs
Practice Tags :
  • Algorithms
  • Data Structures
  • Graph
  • python
  • python-dict

Similar Reads

    Print all shortest paths between given source and destination in an undirected graph
    Given an undirected and unweighted graph and two nodes as source and destination, the task is to print all the paths of the shortest length between the given source and destination.Examples: Input: source = 0, destination = 5 Output: 0 -> 1 -> 3 -> 50 -> 2 -> 3 -> 50 -> 1 ->
    13 min read
    Difference between the shortest and second shortest path in an Unweighted Bidirectional Graph
    Given an unweighted bidirectional graph containing N nodes and M edges represented by an array arr[][2]. The task is to find the difference in length of the shortest and second shortest paths from node 1 to N. If the second shortest path does not exist, print 0. Note: The graph is connected, does no
    15+ min read
    Shortest path with one curved edge in an undirected Graph
    Given an undirected connected graph of n vertices and a list of m edges in a graph and for each pair of vertices that are connected by an edge. There are two edges between them, one curved edge and one straight edge i.e. the tuple (x, y, w1, w2) means that between vertices x and y, there is a straig
    12 min read
    Number of shortest paths in an unweighted and directed graph
    Given an unweighted directed graph, can be cyclic or acyclic. Print the number of shortest paths from a given vertex to each of the vertices. For example consider the below graph. There is one shortest path vertex 0 to vertex 0 (from each vertex there is a single shortest path to itself), one shorte
    11 min read
    Shortest path with exactly k edges in a directed and weighted graph | Set 2
    Given a directed weighted graph and two vertices S and D in it, the task is to find the shortest path from S to D with exactly K edges on the path. If no such path exists, print -1. Examples: Input: N = 3, K = 2, ed = {{{1, 2}, 5}, {{2, 3}, 3}, {{3, 1}, 4}}, S = 1, D = 3 Output: 8 Explanation: The s
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences