Difference between the shortest and second shortest path in an Unweighted Bidirectional Graph - GeeksforGeeks

26 Oct, 2021
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<=20)
Examples:
Input: N = 4, M = 4, arr[M][2]={{1, 2}, {2, 3}, {3, 4}, {1, 4}}Output: 2Explanation: The shortest path is 1->4 and the second shortest path is 1->2->3->4. Hence, the difference is 2.
Input: N = 6, M = 8, arr[M][2]={{1, 2}, {1, 3}, {2, 6}, {2, 3}, {2, 4}, {3, 4}, {3, 5}, {4, 6}}Output:1
Approach: The idea is to Depth First Search to find all possible paths and store them in vector and sort the vector and find the difference between the shortest and the second shortest path. Follow the steps below to solve the problem:
Define a function dfs(vector<vector<int> >& graph, int s, int e, vector<int> vis, int count, vector<int>& dp) and perform the following steps:If s is equal to e, then it means that the current path is one of the possible ones, push the value of count in the vector dp[] and return.Iterate over the range [0, graph[s]] using the variable i and performing the following steps:If vis[i] is not equal to 1, then set the value of vis[i] to 1 and call the function dfs(graph, i, e, vis, count+1, dp) to find other possible paths and set the value of vis[0] again back to 0.
If s is equal to e, then it means that the current path is one of the possible ones, push the value of count in the vector dp[] and return.
Iterate over the range [0, graph[s]] using the variable i and performing the following steps:If vis[i] is not equal to 1, then set the value of vis[i] to 1 and call the function dfs(graph, i, e, vis, count+1, dp) to find other possible paths and set the value of vis[0] again back to 0.
If vis[i] is not equal to 1, then set the value of vis[i] to 1 and call the function dfs(graph, i, e, vis, count+1, dp) to find other possible paths and set the value of vis[0] again back to 0.
Initialize a 2-D vector graph[][] with N number of rows to store the vertices connected from each vertex.
Iterate over the range [0, M] using the variable i and perform the following steps:Push the value of b-1 in the vector graph[][] in row a-1.Push the value of a-1 in the vector graph[][] in row b-1.
Push the value of b-1 in the vector graph[][] in row a-1.
Push the value of a-1 in the vector graph[][] in row b-1.
Initialize a vector vis[] of size N to keep track of visited nodes.
Initialize a vector dp[] to store the length of all possible paths.
Call the function dfs(graph, 0, N-1, vis, 0, dp) to find all possible paths and store them in the vector dp[].
Sort the vector dp[] in ascending order.
If the size of vector dp[] is greater than 1, then return the value dp[1]-dp[0] else return 0 as the answer.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // DFS function to find all possible paths.void dfs(vector<vector<int> >& graph, int s, int e,         vector<int> v, int count, vector<int>& dp){    if (s == e) {        // Push the number of nodes required for        // one of the possible paths        dp.push_back(count);        return;    }    for (auto i : graph[s]) {        if (v[i] != 1) {             // Mark the node as visited and            // call the function to search for            // possible paths and unmark the node.            v[i] = 1;            dfs(graph, i, e, v, count + 1, dp);            v[i] = 0;        }    }} // Function to find the difference between the// shortest and second shortest pathvoid findDifference(int n, int m, int arr[][2]){    // Construct the graph    vector<vector<int> > graph(n, vector<int>());    for (int i = 0; i < m; i++) {        int a, b;        a = arr[i][0];        b = arr[i][1];        graph[a - 1].push_back(b - 1);        graph[b - 1].push_back(a - 1);    }     // Vector to mark the nodes as visited or not.    vector<int> v(n, 0);     // Vector to store the count of all possible paths.    vector<int> dp;     // Mark the starting node as visited.    v[0] = 1;     // Function to find all possible paths.    dfs(graph, 0, n - 1, v, 0, dp);     // Sort the vector    sort(dp.begin(), dp.end());     // Print the difference    if (dp.size() != 1)        cout << dp[1] - dp[0];    else        cout << 0;} // Driver Codeint main(){    int n, m;    n = 6;    m = 8;    int arr[m][2]        = { { 1, 2 }, { 1, 3 },            { 2, 6 }, { 2, 3 },            { 2, 4 }, { 3, 4 },            { 3, 5 }, { 4, 6 } };     findDifference(n, m, arr);     return 0;}
// Java program for the above approachimport java.util.*;public class Main{    // DFS function to find all possible paths.    static void dfs(Vector<Vector<Integer>> graph, int s,                    int e, int[] v, int count, Vector<Integer> dp) {      if (s == e)      {                // Push the number of nodes required for        // one of the possible paths        dp.add(count);        return;      }      for(int i : graph.get(s)) {        if (v[i] != 1)        {                    // Mark the node as visited and          // call the function to search for          // possible paths and unmark the node.          v[i] = 1;          dfs(graph, i, e, v, count + 1, dp);          v[i] = 0;        }      }    }          // Function to find the difference between the    // shortest and second shortest path    static void findDifference(int n, int m, int[][] arr)    {            // Construct the graph      Vector<Vector<Integer>> graph = new Vector<Vector<Integer>>();      for(int i = 0; i < n; i++)      {        graph.add(new Vector<Integer>());      }            for (int i = 0; i < m; i++) {        int a, b;        a = arr[i][0];        b = arr[i][1];        graph.get(a - 1).add(b - 1);        graph.get(b - 1).add(a - 1);      }            // Vector to mark the nodes as visited or not.      int[] v = new int[n];      Arrays.fill(v, 0);            // Vector to store the count of all possible paths.      Vector<Integer> dp = new Vector<Integer>();            // Mark the starting node as visited.      v[0] = 1;            // Function to find all possible paths.      dfs(graph, 0, n - 1, v, 0, dp);            // Sort the vector      Collections.sort(dp);            // Print the difference      if (dp.size() != 1) System.out.print(dp.get(1) - dp.get(0));      else System.out.print(0);    }         public static void main(String[] args) {        int n, m;        n = 6;        m = 8;        int[][] arr            = { { 1, 2 }, { 1, 3 },                { 2, 6 }, { 2, 3 },                { 2, 4 }, { 3, 4 },                { 3, 5 }, { 4, 6 } };              findDifference(n, m, arr);    }} // This code is contributed by mukesh07.
# Python3 program for the above approach # DFS function to find all possible paths.def dfs(graph, s, e, v, count, dp):  if (s == e):         # Push the number of nodes required for    # one of the possible paths    dp.append(count)    return  for i in graph[s]:    if (v[i] != 1):             # Mark the node as visited and      # call the function to search for      # possible paths and unmark the node.      v[i] = 1      dfs(graph, i, e, v, count + 1, dp)      v[i] = 0  # Function to find the difference between the# shortest and second shortest pathdef findDifference(n, m, arr):  # Construct the graph  graph = []  for i in range(n):      graph.append([])    for i in range(m):    a = arr[i][0]    b = arr[i][1]    graph[a - 1].append(b - 1)    graph[b - 1].append(a - 1)    # Vector to mark the nodes as visited or not.  v = [0]*(n)    # Vector to store the count of all possible paths.  dp = []    # Mark the starting node as visited.  v[0] = 1    # Function to find all possible paths.  dfs(graph, 0, n - 1, v, 0, dp)    # Sort the vector  dp.sort()    # Print the difference  if (len(dp) != 1):    print(dp[1] - dp[0], end = "")  else:    print(0, end = "") # Driver Coden = 6m = 8arr = [  [1, 2],  [1, 3],  [2, 6],  [2, 3],  [2, 4],  [3, 4],  [3, 5],  [4, 6],]  findDifference(n, m, arr) # This code is contributed by divyesh072019.
// C# program for the above approachusing System;using System.Collections.Generic;class GFG {         // DFS function to find all possible paths.    static void dfs(List<List<int>> graph, int s, int e, List<int> v, int count, List<int> dp) {      if (s == e)      {                // Push the number of nodes required for        // one of the possible paths        dp.Add(count);        return;      }      foreach(int i in graph[s]) {        if (v[i] != 1)        {                    // Mark the node as visited and          // call the function to search for          // possible paths and unmark the node.          v[i] = 1;          dfs(graph, i, e, v, count + 1, dp);          v[i] = 0;        }      }    }          // Function to find the difference between the    // shortest and second shortest path    static void findDifference(int n, int m, int[,] arr)    {            // Construct the graph      List<List<int>> graph = new List<List<int>>();      for(int i = 0; i < n; i++)      {          graph.Add(new List<int>());      }            for (int i = 0; i < m; i++) {        int a, b;        a = arr[i,0];        b = arr[i,1];        graph[a - 1].Add(b - 1);        graph[b - 1].Add(a - 1);      }            // Vector to mark the nodes as visited or not.      List<int> v = new List<int>();      for(int i = 0; i < n; i++)      {          v.Add(0);      }            // Vector to store the count of all possible paths.      List<int> dp = new List<int>();            // Mark the starting node as visited.      v[0] = 1;            // Function to find all possible paths.      dfs(graph, 0, n - 1, v, 0, dp);            // Sort the vector      dp.Sort();            // Print the difference      if (dp.Count != 1) Console.Write(dp[1] - dp[0]);      else Console.Write(0);    }   static void Main() {    int n, m;    n = 6;    m = 8;    int[,] arr        = { { 1, 2 }, { 1, 3 },            { 2, 6 }, { 2, 3 },            { 2, 4 }, { 3, 4 },            { 3, 5 }, { 4, 6 } };      findDifference(n, m, arr);  }} // Ths code is contributed by decode2207.
<script>// Javascript program for the above approach // DFS function to find all possible paths.function dfs(graph, s, e, v, count, dp) {  if (s == e)  {       // Push the number of nodes required for    // one of the possible paths    dp.push(count);    return;  }  for (let i of graph[s]) {    if (v[i] != 1)    {           // Mark the node as visited and      // call the function to search for      // possible paths and unmark the node.      v[i] = 1;      dfs(graph, i, e, v, count + 1, dp);      v[i] = 0;    }  }} // Function to find the difference between the// shortest and second shortest pathfunction findDifference(n, m, arr){   // Construct the graph  let graph = new Array(n).fill(0).map(() => []);   for (let i = 0; i < m; i++) {    let a, b;    a = arr[i][0];    b = arr[i][1];    graph[a - 1].push(b - 1);    graph[b - 1].push(a - 1);  }   // Vector to mark the nodes as visited or not.  let v = new Array(n).fill(0);   // Vector to store the count of all possible paths.  let dp = [];   // Mark the starting node as visited.  v[0] = 1;   // Function to find all possible paths.  dfs(graph, 0, n - 1, v, 0, dp);   // Sort the vector  dp.sort((a, b) => a - b);   // Print the difference  if (dp.length != 1) document.write(dp[1] - dp[0]);  else document.write(0);} // Driver Codelet n, m;n = 6;m = 8;let arr = [  [1, 2],  [1, 3],  [2, 6],  [2, 3],  [2, 4],  [3, 4],  [3, 5],  [4, 6],]; findDifference(n, m, arr); // This code is contributed by gfgking.</script>
  
1
 
Time Complexity: O(2^N)Auxiliary Space: O(N)
 
Efficient Approach: Using the fact that the second shortest path can not contain all the edges same as that in the shortest path. Remove each edge of the shortest path one at a time and keep finding the shortest path, then one of them has to be the required second shortest path. Use Breadth First Search to find the solution optimally. Follow the steps below to solve the problem:
 
Define a function get_edges(int s, vector<int>& edges, vector<int> p) and perform the following steps:If s is equal to -1, then return.Call the function get_edges(p[s], edges, p) to find all the edges along the shortest path.Push the value of s in the vector edges[].
If s is equal to -1, then return.
Call the function get_edges(p[s], edges, p) to find all the edges along the shortest path.
Push the value of s in the vector edges[].
Define a function dist_helper(vector<vector<int> > graph, vector<int>& d, int v1, int v2, int N) and perform the following steps:Initialize the vector vis[] to keep track of visited nodes.Initialize a queue of pairs q[] to do the Breadth First Search and find the path.Enqueue the pair {0, 0} into the queue of pairs q[].Mark the value of vis[0] as 1(visited).Iterate in a while loop till the queue of pairs q[] is not empty.Initialize a variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If i is equal to v1 and a.first is equal to v2 or i is equal to v2 and a.first is equal to v1, then continue.If vis[i] is equal to 0, then set the value of d[i] as 1+a.second, p[i] as a.first and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[].
Initialize the vector vis[] to keep track of visited nodes.
Initialize a queue of pairs q[] to do the Breadth First Search and find the path.
Enqueue the pair {0, 0} into the queue of pairs q[].
Mark the value of vis[0] as 1(visited).
Iterate in a while loop till the queue of pairs q[] is not empty.Initialize a variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If i is equal to v1 and a.first is equal to v2 or i is equal to v2 and a.first is equal to v1, then continue.If vis[i] is equal to 0, then set the value of d[i] as 1+a.second, p[i] as a.first and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[].
Initialize a variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].
Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If i is equal to v1 and a.first is equal to v2 or i is equal to v2 and a.first is equal to v1, then continue.If vis[i] is equal to 0, then set the value of d[i] as 1+a.second, p[i] as a.first and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[].
If i is equal to v1 and a.first is equal to v2 or i is equal to v2 and a.first is equal to v1, then continue.
If vis[i] is equal to 0, then set the value of d[i] as 1+a.second, p[i] as a.first and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[].
Define a function dist(vector<vector<int> > graph, vector<int>& d, vector<int> &p, int N) and perform the following steps:Initialize the vector vis[] to keep track of visited nodes.Initialize a queue of pairs q[] to do the Breadth First Search and find the path.Enqueue the pair {0, 0} into the queue of pairs q[].Mark the value of vis[0] as 1(visited).Iterate in a while loop till the queue of pairs q[] is not empty.Initialize the variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If vis[i] is equal to 0, then set the value of d[i] as 1+a.second and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[].
Initialize the vector vis[] to keep track of visited nodes.
Initialize a queue of pairs q[] to do the Breadth First Search and find the path.
Enqueue the pair {0, 0} into the queue of pairs q[].
Mark the value of vis[0] as 1(visited).
Iterate in a while loop till the queue of pairs q[] is not empty.Initialize the variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If vis[i] is equal to 0, then set the value of d[i] as 1+a.second and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[].
Initialize the variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].
Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If vis[i] is equal to 0, then set the value of d[i] as 1+a.second and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[].
If vis[i] is equal to 0, then set the value of d[i] as 1+a.second and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[].
Initialize a 2-D vector graph[][] with N number of rows to store the vertices connected from each vertex.
Iterate over the range [0, M] using the variable i and perform the following steps:Push the value of b-1 in the vector graph[][] in row a-1.Push the value of a-1 in the vector graph[][] in row b-1.
Push the value of b-1 in the vector graph[][] in row a-1.
Push the value of a-1 in the vector graph[][] in row b-1.
Initialize the vectors p[] and d[] of size N to keep track of parent nodes and the length of the paths.
Call the function dist(graph, d, p, N) to find the length of the shortest path.
Initialize a vector distances[] to store the length of all possible paths.
Push the value of d[N-1] in the vector distances[].
Initialize a vector edges[] to get all the edges along the shortest path.
Call the function get_edges(N-1, edges, p) to find all the edges along the shortest path.
Iterate over the range [0, edges.size()-1] using the variable i and perform the following steps:Call the function dist_helper(graph, d, edges[i], edges[i+1], N) to find all the edges along the shortest path.Push the value of d[N-1] in the vector distances[].
Call the function dist_helper(graph, d, edges[i], edges[i+1], N) to find all the edges along the shortest path.
Push the value of d[N-1] in the vector distances[].
Sort the vector distances[] in ascending order.
If the size of vector distances[] is greater than 1, then return the value distances[1]-distances[0] else return 0 as the answer.
 
Below is the implementation of the above approach.
 
C++
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to get all the edges in// the shortest pathvoid get_edges(int s, vector<int>& edges, vector<int> p){    if (s == -1)        return;    get_edges(p[s], edges, p);    edges.push_back(s);} // Calculate the shortest distance// after removing an edge between// v1 and v2void dist_helper(vector<vector<int> > graph, vector<int>& d,                 int v1, int v2, int n){    // Vector to mark the nodes visited    vector<int> v(n, 0);     // For BFS    queue<pair<int, int> > q;    q.push(make_pair(0, 0));    v[0] = 1;     // Iterate over the range    while (!q.empty()) {        auto a = q.front();        q.pop();        for (int i : graph[a.first]) {            if ((i == v1 && a.first == v2)                || (i == v2 && a.first == v1))                continue;            if (v[i] == 0) {                d[i] = 1 + a.second;                v[i] = 1;                q.push(make_pair(i, d[i]));            }        }    }} // Calculates the shortest distances and// maintain a parent arrayvoid dist(vector<vector<int> > graph, vector<int>& d,          vector<int>& p, int n){    // Vector to mark the nodes visited    vector<int> v(n, 0);     // For BFS    queue<pair<int, int> > q;    q.push(make_pair(0, 0));    v[0] = 1;     // Iterate over the range    while (!q.empty()) {        auto a = q.front();        q.pop();        for (int i : graph[a.first]) {            if (v[i] == 0) {                p[i] = a.first;                d[i] = 1 + a.second;                v[i] = 1;                q.push(make_pair(i, d[i]));            }        }    }} // Function to find the difference between the// shortest and second shortest pathvoid findDifference(int n, int m, int arr[][2]){     // Initializing and constructing the graph    vector<vector<int> > graph(n, vector<int>());    for (int i = 0; i < m; i++) {        int a, b;        a = arr[i][0];        b = arr[i][1];        graph[a - 1].push_back(b - 1);        graph[b - 1].push_back(a - 1);    }     // Initializing the arrays    vector<int> p(n, -1);    vector<int> d(n, 1e9);     // Calculate the shortest path    dist(graph, d, p, n);     // Vector to store the lengths    // of possible paths    vector<int> distances;    distances.push_back(d[n - 1]);     vector<int> edges;     // Get all the edges along the shortest path    get_edges(n - 1, edges, p);     // Iterate over the range    for (int i = 0; i + 1 < edges.size(); i++) {        // Calculate shortest distance after        // removing the edge        dist_helper(graph, d, edges[i], edges[i + 1], n);        distances.push_back(d[n - 1]);    }     // Sort the paths in ascending order    sort(distances.begin(), distances.end());    if (distances.size() == 1)        cout << 0 << endl;    else        cout << distances[1] - distances[0] << endl;} // Driver Codeint main(){    int n, m;    n = 6;    m = 8;    int arr[m][2]        = { { 1, 2 }, { 1, 3 },            { 2, 6 }, { 2, 3 },            { 2, 4 }, { 3, 4 },            { 3, 5 }, { 4, 6 } };     findDifference(n, m, arr);     return 0;}
# Python3 program for the above approach edges, d, p = [], [], [] # Function to get all the edges in# the shortest pathdef get_edges(s):    global edges, d, p    if s == -1:        return    get_edges(p[s])    edges.append(s)  # Calculate the shortest distance# after removing an edge between# v1 and v2def dist_helper(graph, v1, v2, n):    global edges, d, p    # Vector to mark the nodes visited    v = [0]*(n)      # For BFS    q = []    q.append([0, 0])    v[0] = 1      # Iterate over the range    while len(q) > 0:        a = q[0]        q.pop(0)        for i in graph[a[0]]:            if (i == v1 and a[0] == v2) or (i == v2 and a[0] == v1):                continue            if v[i] == 0:                d[i] = 1 + a[1]                v[i] = 1                q.append([i, d[i]])  # Calculates the shortest distances and# maintain a parent arraydef dist(graph, n):    global edges, d, p    # Vector to mark the nodes visited    v = [0]*(n)      # For BFS    q = []    q.append([0, 0])    v[0] = 1      # Iterate over the range    while len(q) > 0:        a = q[0]        q.pop(0)        for i in graph[a[0]]:            if v[i] == 0:                p[i] = a[0]                d[i] = 1 + a[1]                v[i] = 1                q.append([i, d[i]])  # Function to find the difference between the# shortest and second shortest pathdef findDifference(n, m, arr):    global edges, d, p    # Initializing and constructing the graph    graph = []    for i in range(n):        graph.append([])    for i in range(m):        a = arr[i][0]        b = arr[i][1]        graph[a - 1].append(b - 1)        graph[b - 1].append(a - 1)      # Initializing the arrays    p = [-1]*(n)    d = [1e9]*(n)      # Calculate the shortest path    dist(graph, n)      # Vector to store the lengths    # of possible paths    distances = []    distances.append(d[n - 1])      edges = []      # Get all the edges along the shortest path    get_edges(n - 1)      # Iterate over the range    i = 0    while i + 1 < len(edges):               # Calculate shortest distance after        # removing the edge        dist_helper(graph, edges[i], edges[i + 1], n)        distances.append(d[n - 1])        i+=1      # Sort the paths in ascending order    distances.sort()    if len(distances) == 1:        print(0)    else:        print(distances[1] - distances[0]) n = 6;m = 8;arr = [ [ 1, 2 ], [ 1, 3 ], [ 2, 6 ], [ 2, 3 ], [ 2, 4 ], [ 3, 4 ], [ 3, 5 ], [ 4, 6 ] ] findDifference(n, m, arr) # This code is contributed by suresh07.
// C# program for the above approachusing System;using System.Collections.Generic;class GFG {        static List<int> edges = new List<int>();   static List<int> d = new List<int>();   static List<int> p = new List<int>();         // Function to get all the edges in    // the shortest path    static void get_edges(int s)    {        if (s == -1)            return;        get_edges(p[s]);        edges.Add(s);    }      // Calculate the shortest distance    // after removing an edge between    // v1 and v2    static void dist_helper(List<List<int>> graph, int v1, int v2, int n)    {        // Vector to mark the nodes visited        List<int> v = new List<int>();        for(int i = 0; i < n; i++)        {            v.Add(0);        }          // For BFS        List<Tuple<int,int>> q = new List<Tuple<int,int>>();        q.Add(new Tuple<int,int>(0, 0));        v[0] = 1;          // Iterate over the range        while (q.Count > 0) {            Tuple<int,int> a = q[0];            q.RemoveAt(0);            for (int i = 0; i < graph[a.Item1].Count; i++) {                if ((graph[a.Item1][i] == v1 && a.Item1 == v2)                    || (graph[a.Item1][i] == v2 && a.Item1 == v1))                    continue;                if (v[graph[a.Item1][i]] == 0) {                    d[graph[a.Item1][i]] = 1 + a.Item2;                    v[graph[a.Item1][i]] = 1;                    q.Add(new Tuple<int,int>(graph[a.Item1][i], d[graph[a.Item1][i]]));                }            }        }    }      // Calculates the shortest distances and    // maintain a parent array    static void dist(List<List<int>> graph, int n)    {        // Vector to mark the nodes visited        List<int> v = new List<int>();        for(int i = 0; i < n; i++)        {            v.Add(0);        }          // For BFS        List<Tuple<int,int>> q = new List<Tuple<int,int>>();        q.Add(new Tuple<int,int>(0, 0));        v[0] = 1;          // Iterate over the range        while (q.Count > 0) {            Tuple<int,int> a = q[0];            q.RemoveAt(0);            for (int i = 0; i < graph[a.Item1].Count; i++) {                if (v[graph[a.Item1][i]] == 0) {                    p[graph[a.Item1][i]] = a.Item1;                    d[graph[a.Item1][i]] = 1 + a.Item2;                    v[graph[a.Item1][i]] = 1;                    q.Add(new Tuple<int,int>(graph[a.Item1][i], d[graph[a.Item1][i]]));                }            }        }    }      // Function to find the difference between the    // shortest and second shortest path    static void findDifference(int n, int m, int[,] arr)    {          // Initializing and constructing the graph        List<List<int>> graph = new List<List<int>>();        for(int i = 0; i < n; i++)        {            graph.Add(new List<int>());        }        for (int i = 0; i < m; i++) {            int a, b;            a = arr[i,0];            b = arr[i,1];            graph[a - 1].Add(b - 1);            graph[b - 1].Add(a - 1);        }          // Initializing the arrays        for(int i = 0; i < n; i++)        {            p.Add(-1);            d.Add(1000000000);        }          // Calculate the shortest path        dist(graph, n);          // Vector to store the lengths        // of possible paths        List<int> distances = new List<int>();        distances.Add(d[n - 1]);          // Get all the edges along the shortest path        get_edges(n - 1);          // Iterate over the range        for (int i = 0; i + 1 < edges.Count; i++) {            // Calculate shortest distance after            // removing the edge            dist_helper(graph, edges[i], edges[i + 1], n);            distances.Add(d[n - 1]);        }          // Sort the paths in ascending order        distances.Sort();        if (distances.Count == 1)        {            Console.WriteLine(0);        }        else        {            Console.WriteLine((distances[1] - distances[0]));        }    }       // Driver code  static void Main() {    int n, m;    n = 6;    m = 8;    int[,] arr        = { { 1, 2 }, { 1, 3 },            { 2, 6 }, { 2, 3 },            { 2, 4 }, { 3, 4 },            { 3, 5 }, { 4, 6 } };      findDifference(n, m, arr);  }} // This code is contributed by divyeshrabadiya07.
<script>    // Javascript program for the above approach         let edges = [], d = [], p = [];            // Function to get all the edges in    // the shortest path    function get_edges(s)    {        if (s == -1)            return;        get_edges(p[s]);        edges.push(s);    }     // Calculate the shortest distance    // after removing an edge between    // v1 and v2    function dist_helper(graph, v1, v2, n)    {        // Vector to mark the nodes visited        let v = [];        for(let i = 0; i < n; i++)        {            v.push(0);        }         // For BFS        let q = [];        q.push([0, 0]);        v[0] = 1;         // Iterate over the range        while (q.length > 0) {            let a = q[0];            q.shift();            for (let i = 0; i < graph[a[0]].length; i++) {                if ((graph[a[0]][i] == v1 && a[0] == v2)                    || (graph[a[0]][i] == v2 && a[0] == v1))                    continue;                if (v[graph[a[0]][i]] == 0) {                    d[graph[a[0]][i]] = 1 + a[1];                    v[graph[a[0]][i]] = 1;                    q.push([graph[a[0]][i], d[graph[a[0]][i]]]);                }            }        }    }     // Calculates the shortest distances and    // maintain a parent array    function dist(graph, n)    {        // Vector to mark the nodes visited        let v = [];        for(let i = 0; i < n; i++)        {            v.push(0);        }         // For BFS        let q = [];        q.push([0, 0]);        v[0] = 1;         // Iterate over the range        while (q.length > 0) {            let a = q[0];            q.shift();            for (let i = 0; i < graph[a[0]].length; i++) {                if (v[graph[a[0]][i]] == 0) {                    p[graph[a[0]][i]] = a[0];                    d[graph[a[0]][i]] = 1 + a[1];                    v[graph[a[0]][i]] = 1;                    q.push([graph[a[0]][i], d[graph[a[0]][i]]]);                }            }        }    }     // Function to find the difference between the    // shortest and second shortest path    function findDifference(n, m, arr)    {         // Initializing and constructing the graph        let graph = [];        for(let i = 0; i < n; i++)        {            graph.push([]);        }        for (let i = 0; i < m; i++) {            let a, b;            a = arr[i][0];            b = arr[i][1];            graph[a - 1].push(b - 1);            graph[b - 1].push(a - 1);        }         // Initializing the arrays        for(let i = 0; i < n; i++)        {            p.push(-1);            d.push(1e9);        }         // Calculate the shortest path        dist(graph, n);         // Vector to store the lengths        // of possible paths        let distances = [];        distances.push(d[n - 1]);         // Get all the edges along the shortest path        get_edges(n - 1);         // Iterate over the range        for (let i = 0; i + 1 < edges.length; i++) {            // Calculate shortest distance after            // removing the edge            dist_helper(graph, edges[i], edges[i + 1], n);            distances.push(d[n - 1]);        }         // Sort the paths in ascending order        distances.sort(function(a, b){return a - b});        if (distances.length == 1)        {            document.write(0 + "</br>");        }        else        {            document.write((distances[1] - distances[0]) + "</br>");        }    }         let n, m;    n = 6;    m = 8;    let arr        = [ [ 1, 2 ], [ 1, 3 ],            [ 2, 6 ], [ 2, 3 ],            [ 2, 4 ], [ 3, 4 ],            [ 3, 5 ], [ 4, 6 ] ];      findDifference(n, m, arr); // This code is contributed by rameshtravel07.</script>
  
1
 
Time Complexity: O(N*M)Auxiliary Space: O(N)
 
gfgking
divyesh072019
decode2207
mukesh07
suresh07
rameshtravel07
divyeshrabadiya07
Shortest Path
Graph
Recursion
Recursion
Graph
Shortest Path
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Best First Search (Informed Search)
Find if there is a path between two vertices in a directed graph
Eulerian path and circuit for undirected graph
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
Write a program to print all permutations of a given string
Program for Tower of Hanoi
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Sum of the digits of a given number