Generating Random Graphs and Shortest Paths

  • Share this:

Code introduction


This function generates a random graph with a specified number of nodes and edges, and finds the shortest path between all pairs of nodes in the graph.


Technology Stack : NetworkX

Code Type : Function

Code Difficulty : Intermediate


                
                    
import networkx as nx
import random

def generate_random_graph(num_nodes, num_edges):
    # Generate a random graph with specified number of nodes and edges
    G = nx.gnm_random_graph(num_nodes, num_edges)
    
    # Find the shortest path between all pairs of nodes
    all_pairs_shortest_path = nx.all_pairs_shortest_path(G)
    
    return G, all_pairs_shortest_path                
              
Tags: