Open In App

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

Last Updated : 15 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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

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

 



Similar Reads

What is Undirected Graph? | Undirected Graph meaning
An undirected graph is a type of graph where the edges have no specified direction assigned to the them. Characteristics of an Undirected Graph:Edges in an undirected graph are bidirectional in nature.In an undirected graph, there is no concept of a "parent" or "child" vertex as there is no direction to the edges.An undirected graph may contain loo
2 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 straight edge with weight w1 and a curved edge with weig
13 min read
Check if a triplet of buildings can be selected such that the third building is taller than the first building and smaller than the second building
Given an array arr[] consisting of N integers, where each array element represents the height of a building situated on the X co-ordinates, the task is to check if it is possible to select 3 buildings, such that the third selected building is taller than the first selected building and shorter than the second selected building. Examples: Input: arr
12 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 not contain multiple edges and self loops. (2<=N
15+ min read
Queries on Graph for finding shortest path with maximum coins
Given an unweighted directed graph with N vertices and M edges and array A[] of size N. Given Q queries of the form (U, V), the task for this problem is for every query to print the shortest path from U to V and print the maximum coins collected for that shortest path. For visiting, Node 'i' collects A[i] coins. If traveling from U to V is not poss
12 min read
Convert the undirected graph into directed graph such that there is no path of length greater than 1
Given an undirected graph with N vertices and M edges and no self loops or multiple edges. The task is to convert the given undirected graph into a directed graph such that there is no path of length greater than 1. If it is possible to make such a graph then print two space-separated integers u and v in M lines where u, v denotes source and destin
10 min read
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 -> 4 -> 5 Explanation: All the above paths are of
13 min read
Shortest cycle in an undirected unweighted graph
Given an undirected unweighted graph. The task is to find the length of the shortest cycle in the given graph. If no cycle exists print -1. Examples: Input: Output: 4 Cycle 6 -> 1 -> 5 -> 0 -> 6 Input: Output: 3 Cycle 6 -> 1 -> 2 -> 6 Prerequisites: Dijkstra Approach: For every vertex, we check if it is possible to get the shor
8 min read
Number of shortest paths in an Undirected Weighted Graph
Given a weighted undirected graph G and an integer S, the task is to print the distances of the shortest paths and the count of the number of the shortest paths for each node from a given vertex, S. Examples: Input: S =1, G = Output: Shortest Paths distances are : 0 1 2 4 5 3 2 1 3 Numbers of the shortest Paths are: 1 1 1 2 3 1 1 1 2 Explanation: T
15 min read
Finding shortest path between any two nodes using Floyd Warshall Algorithm
Given a graph and two nodes u and v, the task is to print the shortest path between u and v using the Floyd Warshall algorithm. Examples: Input: u = 1, v = 3 Output: 1 -> 2 -> 3 Explanation: Shortest path from 1 to 3 is through vertex 2 with total cost 3. The first edge is 1 -> 2 with cost 2 and the second edge is 2 -> 3 with cost 1. In
13 min read