Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Comparison of Dijkstra’s and Floyd–Warshall algorithms
Next article icon

Find Maximum Shortest Distance in Each Component of a Graph

Last Updated : 21 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an adjacency matrix graph[][] of a weighted graph consisting of N nodes and positive weights, the task for each connected component of the graph is to find the maximum among all possible shortest distances between every pair of nodes.

Examples:

Input:

Output:

8 0 11 

Explanation: There are three components in the graph namely a, b, c. In component (a) the shortest paths are following:

  1. The shortest distance between 3 and 4 is 5 units.
  2. The shortest distance between 3 and 1 is 1+5=6 units.
  3. The shortest distance between 3 and 5 is 5+3=8 units.
  4. The shortest distance between 1 and 4 is 1 unit.
  5. The shortest distance between 1 and 5 is 1+3=4 units.
  6. The shortest distance between 4 and 5 is 3 units.

Out of these shortest distances:
The maximum shortest distance in component (a) is 8 units between node 3 and node 5.
Similarly, 
The maximum shortest distance in component (b) is 0 units.
The maximum shortest distance in component (c) is 11 units between nodes 2 and 6.

Input:

Output:

7 

Explanation: Since, there is only one component with 2 nodes having an edge between them of distance 7. Therefore, the answer will be 7.

Approach: This given problem can be solved by finding the connected components in the graph using DFS and store the components in a list of lists. Floyd Warshall’s Algorithm can be used to find all-pairs shortest paths in each connected component which is based on Dynamic Programming. After getting the shortest distances of all possible pairs in the graph, find the maximum shortest distances for each and every component in the graph. Follow the steps below to solve the problem:

  • Define a function maxInThisComponent(vector<int> component, vector<vector<int>> graph) and perform the following steps:
    • Initialize the variable maxDistance as INT_MIN and n as the size of the component.
    • Iterate over the range [0, n) using the variable i and perform the following tasks:
      • Iterate over the range [i+1, n) using the variable j and update the value of maxDistance as the maximum of maxDistance or graph[component[i]][component[j]].
    • Return the value of maxDistance as the answer.
  • Initialize a vector visited of size N and initialize the values as false.
  • Initialize vectors, say components[][] and temp[] to store each component of the graph.
  • Using Depth First Search(DFS) find all the components and store them in the vector components[][].
  • Now, call the function floydWarshall(graph, V) to implement Floyd Warshall algorithm to find the shortest distance between all pairs of a component of a graph.
  • Initialize a vector result[] to store the result.
  • Initialize the variable numOfComp as the size of the vector components[][].
  • Iterate over the range [0, numOfComp) using the variable i and call the function maxInThisComponent(components[i], graph) and store the value returned by it in the vector result[].
  • After performing the above steps, print the values of the vector result[] as the answer.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Below dfs function will be used to
// get the connected components of a
// graph and stores all the connected
// nodes in the vector component
void dfs(int src, vector<bool>& visited,
         vector<vector<int> >& graph,
         vector<int>& component, int N)
{
 
    // Mark this vertex as visited
    visited[src] = true;
 
    // Put this node in component vector
    component.push_back(src);
 
    // For all other vertices in graph
    for (int dest = 0; dest < N; dest++) {
 
        // If there is an edge between
        // src and dest i.e., the value
        // of graph[u][v]!=INT_MAX
        if (graph[src][dest] != INT_MAX) {
 
            // If we haven't visited dest
            // then recursively apply
            // dfs on dest
            if (!visited[dest])
                dfs(dest, visited, graph,
                    component, N);
        }
    }
}
 
// Below is the Floyd Warshall Algorithm
// which is based on Dynamic Programming
void floydWarshall(
    vector<vector<int> >& graph, int N)
{
 
    // For every vertex of graph find
    // the shortest distance with
    // other vertices
    for (int k = 0; k < N; k++) {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
 
                // Taking care of integer
                // overflow
                if (graph[i][k] != INT_MAX
                    && graph[k][j] != INT_MAX) {
 
                    // Update distance between
                    // vertex i and j if choosing
                    // k as an intermediate vertex
                    // make a shorter distance
                    if (graph[i][k] + graph[k][j]
                        < graph[i][j])
                        graph[i][j]
                            = graph[i][k] + graph[k][j];
                }
            }
        }
    }
}
 
// Function to find the maximum shortest
// path distance in a component by checking
// the shortest distances between all
// possible pairs of nodes
int maxInThisComponent(vector<int>& component,
                       vector<vector<int> >& graph)
{
    int maxDistance = INT_MIN;
    int n = component.size();
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            maxDistance
                = max(maxDistance,
                      graph[component[i]][component[j]]);
        }
    }
 
    // If the maxDistance is still INT_MIN
    // then return 0 because this component
    // has a single element
    return (maxDistance == INT_MIN
                ? 0
                : maxDistance);
}
 
// Below function uses above two method
// to get the  maximum shortest distances
// in each component of the graph the
// function returns a vector, where each
// element denotes maximum shortest path
// distance for a component
vector<int> maximumShortesDistances(
    vector<vector<int> >& graph, int N)
{
 
    // Find the connected components
    vector<bool> visited(N, false);
    vector<vector<int> > components;
 
    // For storing the nodes in a
    // particular component
    vector<int> temp;
 
    // Now for each unvisited node run
    // the dfs to get the connected
    // component having this unvisited node
    for (int i = 0; i < N; i++) {
        if (!visited[i]) {
 
            // First of all clear the temp
            temp.clear();
            dfs(i, visited, graph, temp, N);
            components.push_back(temp);
        }
    }
 
    // Now for all-pair find the shortest
    // path distances using Floyd Warshall
    floydWarshall(graph, N);
 
    // Now for each component find the
    // maximum shortest distance and
    // store it in result
    vector<int> result;
    int numOfComp = components.size();
    int maxDistance;
    for (int i = 0; i < numOfComp; i++) {
        maxDistance
            = maxInThisComponent(components[i], graph);
        result.push_back(maxDistance);
    }
    return result;
}
 
// Driver Code
int main()
{
    int N = 8;
    const int inf = INT_MAX;
 
    // Adjacency Matrix for the first
    // graph in the examples
    vector<vector<int> > graph1 = {
        { 0, inf, 9, inf, inf, inf, 3, inf },
        { inf, 0, inf, 10, 1, 8, inf, inf },
        { 9, inf, 0, inf, inf, inf, 11, inf },
        { inf, 10, inf, 0, 5, 13, inf, inf },
        { inf, 1, inf, 5, 0, 3, inf, inf },
        { 8, inf, inf, 13, 3, 0, inf, inf },
        { 3, inf, 11, inf, inf, inf, 0, inf },
        { inf, inf, inf, inf, inf, inf, inf, 0 },
    };
 
    // Find the maximum shortest distances
    vector<int> result1
        = maximumShortesDistances(graph1, N);
 
    // Printing the maximum shortest path
    // distances for each components
    for (int mx1 : result1)
        cout << mx1 << ' ';
 
    return 0;
}
 
 

Java




// Java code for the above approach:
 
import java.util.*;
 
public class Main {
    static boolean[] visited;
    // For storing the connected components
    static ArrayList <ArrayList <Integer> > components;
     
    // Below dfs function will be used to
    // get the connected components of a
    // graph and stores all the connected
    // nodes in the vector component
    static void dfs(int[][] graph, ArrayList<Integer> temp,int src, int N)
    {
        // Mark this vertex as visited
        visited[src] = true;
 
        // Put this node in component vector
        temp.add(src);
 
        // For all other vertices in graph
        for (int dest = 0; dest < N; dest++) {
 
            // If there is an edge between
            // src and dest i.e., the value
            // of graph[u][v]!=Integer.MAX_VALUE
            if (graph[src][dest] != Integer.MAX_VALUE) {
 
                // If we haven't visited dest
                // then recursively apply
                // dfs on dest
                if (!visited[dest])
                    dfs(graph, temp, dest, N);
            }
        }
    }
    // Below is the Floyd Warshall Algorithm
    // which is based on Dynamic Programming
    static void floydWarshall(int[][] graph, int N)
    {
        // For every vertex of graph find
        // the shortest distance with
        // other vertices
        for (int k = 0; k < N; k++) {
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
 
                    // Taking care of integer
                    // overflow
                    if (graph[i][k] != Integer.MAX_VALUE
                        && graph[k][j] != Integer.MAX_VALUE) {
 
                        // Update distance between
                        // vertex i and j if choosing
                        // k as an intermediate vertex
                        // make a shorter distance
                        if (graph[i][k] + graph[k][j]
                            < graph[i][j])
                            graph[i][j] = graph[i][k] + graph[k][j];
                    }
                }
            }
        }
    }
    // Function to find the maximum shortest
    // path distance in a component by checking
    // the shortest distances between all
    // possible pairs of nodes
    static int maxInThisComponent(int[][] graph, ArrayList <Integer> component)
    {
        int maxDistance = Integer.MIN_VALUE;
        int n = component.size();
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                maxDistance
                    = Math.max(maxDistance,
                        graph[component.get(i)][component.get(j)]);
            }
        }
 
        // If the maxDistance is still Integer.MIN_VALUE
        // then return 0 because this component
        // has a single element
        return (maxDistance == Integer.MIN_VALUE
                    ? 0
                    : maxDistance);
    }
 
    // Below function uses above two method
    // to get the  maximum shortest distances
    // in each component of the graph the
    // function returns a vector, where each
    // element denotes maximum shortest path
    // distance for a component
    static ArrayList <Integer> maximumShortesDistances(int[][] graph, int N)
    {
        visited = new boolean[N];
        Arrays.fill(visited, false);
        // Find the connected components
        components =  new ArrayList <ArrayList<Integer> > ();
 
        // Now for each unvisited node run
        // the dfs to get the connected
        // component having this unvisited node
        for (int i = 0; i < N; i++) {
            if (!visited[i] ) {
 
                // For storing the nodes in a
                // particular component
                ArrayList<Integer> temp = new ArrayList<Integer> ();
                dfs(graph, temp, i, N);
                components.add(temp);
            }
        }
 
        // Now for all-pair find the shortest
        // path distances using Floyd Warshall
        floydWarshall(graph, N);
 
        // Now for each component find the
        // maximum shortest distance and
        // store it in result
        ArrayList <Integer> result = new ArrayList <Integer> ();
        int numOfComp = components.size();
 
        int maxDistance;
        for (int i = 0; i < numOfComp; i++) {
            maxDistance
                = maxInThisComponent(graph, components.get(i));
            result.add(maxDistance);
        }
        return result;
    }
     
    // Driver Code
    public static void main(String args[]) {
        int N = 8;
        final int inf = Integer.MAX_VALUE;
 
        // Adjacency Matrix for the first
        // graph in the examples
        int[][] graph = {
            { 0, inf, 9, inf, inf, inf, 3, inf },
            { inf, 0, inf, 10, 1, 8, inf, inf },
            { 9, inf, 0, inf, inf, inf, 11, inf },
            { inf, 10, inf, 0, 5, 13, inf, inf },
            { inf, 1, inf, 5, 0, 3, inf, inf },
            { 8, inf, inf, 13, 3, 0, inf, inf },
            { 3, inf, 11, inf, inf, inf, 0, inf },
            { inf, inf, inf, inf, inf, inf, inf, 0 },
        };
 
        // Find the maximum shortest distances
        ArrayList <Integer> result1
            = maximumShortesDistances(graph, N);
 
        // Printing the maximum shortest path
        // distances for each components
        for (int mx1 : result1)
            System.out.print(mx1 + " ");
 
    }
}
 
// This code has been contributed by Sachin Sahara (sachin801)
 
 

Python3




## Python program for the above approach:
 
INT_MAX = 9223372036854775807
INT_MIN = -9223372036854775808
 
## Below dfs function will be used to
## get the connected components of a
## graph and stores all the connected
## nodes in the vector component
def dfs(src, visited, graph, component, N):
 
    ## Mark this vertex as visited
    visited[src] = True
 
    ## Put this node in component vector
    component.append(src);
 
    ## For all other vertices in graph
    for dest in range(0, N):
 
        ## If there is an edge between
        ## src and dest i.e., the value
        ## of graph[u][v]!=INT_MAX
        if (graph[src][dest] != INT_MAX):
 
            ## If we haven't visited dest
            ## then recursively apply
            ## dfs on dest
            if not visited[dest]:
                dfs(dest, visited, graph, component, N);
 
## Below is the Floyd Warshall Algorithm
## which is based on Dynamic Programming
def floydWarshall(graph, N):
 
    ## For every vertex of graph find
    ## the shortest distance with
    ## other vertices
    for k in range(0, N):
        for i in range(0, N):
            for j in range(0, N):
 
                ## Taking care of integer
                ## overflow
                if (graph[i][k] != INT_MAX and graph[k][j] != INT_MAX):
 
                    ## Update distance between
                    ## vertex i and j if choosing
                    ## k as an intermediate vertex
                    ## make a shorter distance
                    if (graph[i][k] + graph[k][j] < graph[i][j]):
                        graph[i][j] = graph[i][k] + graph[k][j];
 
## Function to find the maximum shortest
## path distance in a component by checking
## the shortest distances between all
## possible pairs of nodes
def maxInThisComponent(component, graph):
    maxDistance = INT_MIN;
    n = len(component);
    for i in range(0, n):
        for j in range(i+1, n):
            maxDistance = max(maxDistance, graph[component[i]][component[j]])
 
    ## If the maxDistance is still INT_MIN
    ## then return 0 because this component
    ## has a single element
    if maxDistance == INT_MIN:
        return 0
    return maxDistance
 
## Below function uses above two method
## to get the maximum shortest distances
## in each component of the graph the
## function returns a vector, where each
## element denotes maximum shortest path
## distance for a component
def maximumShortesDistances(graph, N):
 
    ## Find the connected components
    visited = []
    for i in range(0, N):
        visited.append(False)
     
    components = []
     
 
    ## Now for each unvisited node run
    ## the dfs to get the connected
    ## component having this unvisited node
    for i in range(0, N):
        if not visited[i]:
 
            ## For storing the nodes in a
            ## particular component
            temp = []
            dfs(i, visited, graph, temp, N)
            components.append(temp)
 
    ## Now for all-pair find the shortest
    ## path distances using Floyd Warshall
    floydWarshall(graph, N)
 
    ## Now for each component find the
    ## maximum shortest distance and
    ## store it in result
    result = []
    numOfComp = len(components)
    maxDistance = 0
    for i in range(0, numOfComp):
        maxDistance = maxInThisComponent(components[i], graph)
        result.append(maxDistance)
    return result
 
## Driver code
if __name__=='__main__':
 
    N = 8
    inf = INT_MAX;
 
    ## Adjacency Matrix for the first
    ## graph in the examples
    graph1 = [
        [ 0, inf, 9, inf, inf, inf, 3, inf ],
        [ inf, 0, inf, 10, 1, 8, inf, inf ],
        [ 9, inf, 0, inf, inf, inf, 11, inf ],
        [ inf, 10, inf, 0, 5, 13, inf, inf ],
        [ inf, 1, inf, 5, 0, 3, inf, inf ],
        [ 8, inf, inf, 13, 3, 0, inf, inf ],
        [ 3, inf, 11, inf, inf, inf, 0, inf ],
        [ inf, inf, inf, inf, inf, inf, inf, 0 ],
    ];
 
    ## Find the maximum shortest distances
    result1 = maximumShortesDistances(graph1, N);
 
    ## Printing the maximum shortest path
    ## distances for each components
    for mx1 in result1:
        print(mx1, end = " ")
    print("")
     
    # This code is contributed by subhamgoyal2014.
 
 

Javascript




<script>
// Javascript program for the above approach
 
// Below dfs function will be used to
// get the connected components of a
// graph and stores all the connected
// nodes in the vector component
function dfs(src, visited, graph, component, N)
{
 
  // Mark this vertex as visited
  visited[src] = true;
 
  // Put this node in component vector
  component.push(src);
 
  // For all other vertices in graph
  for (let dest = 0; dest < N; dest++)
  {
   
    // If there is an edge between
    // src and dest i.e., the value
    // of graph[u][v]!=INT_MAX
    if (graph[src][dest] != Number.MAX_SAFE_INTEGER)
    {
     
      // If we haven't visited dest
      // then recursively apply
      // dfs on dest
      if (!visited[dest]) dfs(dest, visited, graph, component, N);
    }
  }
}
 
// Below is the Floyd Warshall Algorithm
// which is based on Dynamic Programming
function floydWarshall(graph, N)
{
 
  // For every vertex of graph find
  // the shortest distance with
  // other vertices
  for (let k = 0; k < N; k++)
  {
    for (let i = 0; i < N; i++)
    {
      for (let j = 0; j < N; j++)
      {
        // Taking care of integer
        // overflow
        if (graph[i][k] != Number.MAX_SAFE_INTEGER && graph[k][j] != Number.MAX_SAFE_INTEGER)
        {
         
          // Update distance between
          // vertex i and j if choosing
          // k as an intermediate vertex
          // make a shorter distance
          if (graph[i][k] + graph[k][j] < graph[i][j])
            graph[i][j] = graph[i][k] + graph[k][j];
        }
      }
    }
  }
}
 
// Function to find the maximum shortest
// path distance in a component by checking
// the shortest distances between all
// possible pairs of nodes
function maxInThisComponent(component, graph) {
  let maxDistance = Number.MIN_SAFE_INTEGER;
  let n = component.length;
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      maxDistance = Math.max(maxDistance, graph[component[i]][component[j]]);
    }
  }
 
  // If the maxDistance is still INT_MIN
  // then return 0 because this component
  // has a single element
  return maxDistance == Number.MIN_SAFE_INTEGER ? 0 : maxDistance;
}
 
// Below function uses above two method
// to get the  maximum shortest distances
// in each component of the graph the
// function returns a vector, where each
// element denotes maximum shortest path
// distance for a component
function maximumShortesDistances(graph, N) {
  // Find the connected components
  let visited = new Array(N).fill(false);
  let components = new Array();
 
  // For storing the nodes in a
  // particular component
  let temp = [];
 
  // Now for each unvisited node run
  // the dfs to get the connected
  // component having this unvisited node
  for (let i = 0; i < N; i++) {
    if (!visited[i]) {
      // First of all clear the temp
      temp = [];
      dfs(i, visited, graph, temp, N);
      components.push(temp);
    }
  }
 
  // Now for all-pair find the shortest
  // path distances using Floyd Warshall
  floydWarshall(graph, N);
 
  // Now for each component find the
  // maximum shortest distance and
  // store it in result
  let result = [];
  let numOfComp = components.length;
  let maxDistance;
  for (let i = 0; i < numOfComp; i++) {
    maxDistance = maxInThisComponent(components[i], graph);
    result.push(maxDistance);
  }
  return result;
}
 
// Driver Code
 
let N = 8;
const inf = Number.MAX_SAFE_INTEGER;
 
// Adjacency Matrix for the first
// graph in the examples
let graph1 = [
  [0, inf, 9, inf, inf, inf, 3, inf],
  [inf, 0, inf, 10, 1, 8, inf, inf],
  [9, inf, 0, inf, inf, inf, 11, inf],
  [inf, 10, inf, 0, 5, 13, inf, inf],
  [inf, 1, inf, 5, 0, 3, inf, inf],
  [8, inf, inf, 13, 3, 0, inf, inf],
  [3, inf, 11, inf, inf, inf, 0, inf],
  [inf, inf, inf, inf, inf, inf, inf, 0],
];
 
// Find the maximum shortest distances
let result1 = maximumShortesDistances(graph1, N);
 
// Printing the maximum shortest path
// distances for each components
for (mx1 of result1) document.write(mx1 + " ");
 
// This code is contributed by gfgking.
</script>
 
 

C#




using System;
using System.Collections.Generic;
 
public class Graph {
    public int N;
    public int[, ] graph;
    public bool[] visited;
    public List<int> component;
 
    public Graph(int N)
    {
        this.N = N;
        graph = new int[N, N];
        visited = new bool[N];
        component = new List<int>();
    }
 
    public void dfs(int src)
    {
        visited[src] = true;
        component.Add(src);
 
        for (int dest = 0; dest < N; dest++) {
            if (graph[src, dest] != Int32.MaxValue
                && !visited[dest])
                dfs(dest);
        }
    }
 
    public void floydWarshall()
    {
        for (int k = 0; k < N; k++)
            for (int i = 0; i < N; i++)
                for (int j = 0; j < N; j++)
                    if (graph[i, k] != Int32.MaxValue
                        && graph[k, j] != Int32.MaxValue)
                        if (graph[i, k] + graph[k, j]
                            < graph[i, j])
                            graph[i, j]
                                = graph[i, k] + graph[k, j];
    }
 
    public int maxInThisComponent(List<int> component)
    {
        int maxDistance = Int32.MinValue;
        int n = component.Count;
 
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                maxDistance = Math.Max(
                    maxDistance,
                    graph[component[i], component[j]]);
 
        return maxDistance == Int32.MinValue ? 0
                                             : maxDistance;
    }
    public List<int> maximumShortesDistances()
    {
        List<List<int> > components
            = new List<List<int> >();
        List<int> temp = new List<int>();
 
        for (int i = 0; i < N; i++) {
            if (!visited[i]) {
                temp.Clear();
                dfs(i);
                components.Add(new List<int>(component));
                component.Clear();
            }
        }
 
        floydWarshall();
 
        List<int> result = new List<int>();
        int numOfComp = components.Count;
        int maxDistance;
 
        for (int i = 0; i < numOfComp; i++) {
            maxDistance = maxInThisComponent(components[i]);
            result.Add(maxDistance);
        }
 
        return result;
    }
}
 
class Program {
    static void Main(string[] args)
    {
        int N = 8;
        int inf = int.MaxValue;
 
        // Adjacency Matrix for the first graph in the
        // examples
        int[, ] graph1 = new int[, ] {
            { 0, inf, 9, inf, inf, inf, 3, inf },
            { inf, 0, inf, 10, 1, 8, inf, inf },
            { 9, inf, 0, inf, inf, inf, 11, inf },
            { inf, 10, inf, 0, 5, 13, inf, inf },
            { inf, 1, inf, 5, 0, 3, inf, inf },
            { 8, inf, inf, 13, 3, 0, inf, inf },
            { 3, inf, 11, inf, inf, inf, 0, inf },
            { inf, inf, inf, inf, inf, inf, inf, 0 },
        };
 
        Graph g = new Graph(N);
        g.graph = graph1;
 
        // Find the maximum shortest distances
        List<int> result1 = g.maximumShortesDistances();
 
        // Printing the maximum shortest path distances for
        // each component
        foreach(int mx1 in result1)
        {
            Console.Write(mx1 + " ");
        }
    }
}
 
 
Output
11 8 0 

Time Complexity: O(N3), where N is the number of vertices in the graph.
Auxiliary Space: O(N)

 



Next Article
Comparison of Dijkstra’s and Floyd–Warshall algorithms
author
sinhadiptiprakash
Improve
Article Tags :
  • Algorithms
  • Data Structures
  • DSA
  • Dynamic Programming
  • Graph
  • DFS
  • Dijkstra
Practice Tags :
  • Algorithms
  • Data Structures
  • DFS
  • Dynamic Programming
  • Graph

Similar Reads

  • What is Dijkstra’s Algorithm? | Introduction to Dijkstra's Shortest Path Algorithm
    In this article, we will be discussing one of the most commonly known shortest-path algorithms i.e. Dijkstra's Shortest Path Algorithm which was developed by Dutch computer scientist Edsger W. Dijkstra in 1956. Moreover, we will do a complexity analysis for this algorithm and also see how it differs
    10 min read
  • Dijkstra's Algorithm to find Shortest Paths from a Source to all
    Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1. Note: The given graph does not contain any negative edge. Exampl
    12 min read
  • Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8
    The Dijkstra's Algorithm, we can either use the matrix representation or the adjacency list representation to represent the graph, while the time complexity of Dijkstra's Algorithm using matrix representation is O(V^2). The time complexity of Dijkstra's Algorithm using adjacency list representation
    15+ min read
  • Printing Paths in Dijkstra's Shortest Path Algorithm
    Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph.We have discussed Dijkstra's Shortest Path algorithm in the below posts.  Dijkstra’s shortest path for adjacency matrix representationDijkstra’s shortest path for adjacency list
    15 min read
  • Why does Dijkstra's Algorithm fail on negative weights?
    Dijkstra's Algorithm: It is a graph searching algorithm that uses a Greedy Approach to find the shortest path from the source node to all other remaining nodes. It solves the single-source shortest path problem for a weighted graph. This algorithm keeps track of the weights of the edges for finding
    4 min read
  • Applications of Dijkstra's shortest path algorithm
    Dijkstra’s algorithm is one of the most popular algorithms for solving many single-source shortest path problems having non-negative edge weight in the graphs i.e., it is to find the shortest distance between two vertices on a graph. It was conceived by computer scientist Edsger W. Dijkstra in 1956
    4 min read
  • Dijkstra's Algorithm in different language

    • C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
      Problem Statement: Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph. What is Dijkstra's Algorithm? Dijkstra's algorithm is very similar to Prim's algorithm for minimum spanning tree. Like Prim's MST, we generate an SPT (shorte
      5 min read

    • Java Program for Dijkstra's shortest path algorithm | Greedy Algo-7
      Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. Dijkstra's algorithm is very similar to Prim's algorithm for minimum spanning tree. Like Prim's MST, we generate a SPT (shortest path tree) with given source as root. We maintain two s
      5 min read

    • Dijkstra's shortest path algorithm in Python
      Given a graph and a source vertex in the graph, find the shortest paths from source to all vertices in the given graph. Dijkstra’s algorithm is a popular algorithm for solving many single-source shortest path problems having non-negative edge weight in the graphs i.e., it is to find the shortest dis
      4 min read

    • C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7
      Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. Dijkstra's algorithm is very similar to Prim's algorithm for minimum spanning tree. Like Prim's MST, we generate a SPT (shortest path tree) with given source as root. We maintain two s
      5 min read

    Different ways to implement Dijkstra's algorithm

    • Dijkstra’s shortest path algorithm using set
      Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1. Example: Input: src = 0, V = 5, edges[][] = [[0, 1, 4], [0, 2, 8
      8 min read

    • Dijkstra's Shortest Path Algorithm using priority_queue of STL
      Given a graph and a source vertex in graph, find shortest paths from source to all vertices in the given graph. Input : Source = 0Output : Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14We have discussed Dijkstra’s shortest Path implementations. Dijkstra’s Algorithm for Adjacenc
      15+ min read

    • Dijkstra's shortest path algorithm in Java using PriorityQueue
      Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate a SPT (shortest path tree) with a given source as a root. We maintain two sets, one set contains vertices included in the shortest-path tree, other set includes vertices not yet included
      5 min read

    Variations of Dijkstra's algorithm

    • Minimum Cost using Dijkstra by Modifying Cost of an Edge
      Given an undirected weighted graph of N nodes and M edges in the form of a tuple lets say {X, Y, Z} such that there is an edge with cost Z between X and Y. We are supposed to compute the minimum cost of traversal from node 1 to N. However, we can perform one operation before the traversal such that
      15 min read

    • Minimum cost path from source node to destination node via an intermediate node
      Given an undirected weighted graph. The task is to find the minimum cost of the path from source node to the destination node via an intermediate node. Note: If an edge is traveled twice, only once weight is calculated as cost. Examples: Input: source = 0, destination = 2, intermediate = 3; Output:
      12 min read

    • Find Maximum Shortest Distance in Each Component of a Graph
      Given an adjacency matrix graph[][] of a weighted graph consisting of N nodes and positive weights, the task for each connected component of the graph is to find the maximum among all possible shortest distances between every pair of nodes. Examples: Input: Output: 8 0 11 Explanation: There are thre
      15+ min read

    • Comparison of Dijkstra’s and Floyd–Warshall algorithms
      Dijkstra AlgorithmDijkstra’s Algorithm is a Single-Source Shortest Path SSSP algorithm, i.e., given a source vertex it finds the shortest path from the source to all other vertices. The idea is to generate a SPT (shortest path tree) with a given source as a root and with two sets, one set contains v
      4 min read

  • Find minimum weight cycle in an undirected graph
    Given an undirected, weighted graph with V vertices numbered from 0 to V-1, and E edges represented as a 2D array edges[][], where each element edges[i] = [u, v, w] denotes an edge between nodes u and v with weight w, and all edge weights are positive integers, your task is to find the minimum weigh
    15+ 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