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

Last Updated : 11 Oct, 2023

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: 2
Explanation: 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

## Difference between the shortest and second shortest path in an Unweighted Bidirectional Graph using DFS:

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.

Below is the implementation of the above approach.

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// DFS function to find all possible paths.` `void` `dfs(vector >& 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 path` `void` `findDifference(``int` `n, ``int` `m, ``int` `arr[][2])` `{` `    ``// Construct the graph` `    ``vector > 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 Code` `int` `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

 `// Java program for the above approach` `import` `java.util.*;` `public` `class` `Main` `{` `    ``// DFS function to find all possible paths.` `    ``static` `void` `dfs(Vector> graph, ``int` `s, ` `                    ``int` `e, ``int``[] v, ``int` `count, Vector 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> graph = ``new` `Vector>();` `      ``for``(``int` `i = ``0``; i < n; i++)` `      ``{` `        ``graph.add(``new` `Vector());` `      ``}` `     `  `      ``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 dp = ``new` `Vector();` `     `  `      ``// 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

 `# 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 path` `def` `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 Code` `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 divyesh072019.`

## C#

 `// C# program for the above approach` `using` `System;` `using` `System.Collections.Generic;` `class` `GFG {` `    `  `    ``// DFS function to find all possible paths.` `    ``static` `void` `dfs(List> 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> graph = ``new` `List>();` `      ``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);` `  ``}` `}`   `// This code is contributed by decode2207.`

## Javascript

 ``

Output

```1
```

Time Complexity: O(2^N)
Auxiliary Space: O(N)

## Difference between the shortest and second shortest path in an Unweighted Bidirectional Graph using BFS:

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:

Below is the implementation of the above approach.

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// Function to get all the edges in` `// the shortest path` `void` `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 v2` `void` `dist_helper(vector > graph, vector<``int``>& d,` `                 ``int` `v1, ``int` `v2, ``int` `n)` `{` `    ``// Vector to mark the nodes visited` `    ``vector<``int``> v(n, 0);`   `    ``// For BFS` `    ``queue > 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 array` `void` `dist(vector > graph, vector<``int``>& d,` `          ``vector<``int``>& p, ``int` `n)` `{` `    ``// Vector to mark the nodes visited` `    ``vector<``int``> v(n, 0);`   `    ``// For BFS` `    ``queue > 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 path` `void` `findDifference(``int` `n, ``int` `m, ``int` `arr[][2])` `{`   `    ``// Initializing and constructing the graph` `    ``vector > 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 Code` `int` `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

 `//Java code for the above approach` `import` `java.util.*;`   `class` `Main {` `    ``// Function to get all the edges in` `    ``// the shortest path` `    ``static` `void` `getEdges(``int` `s, List edges,` `                         ``int``[] p)` `    ``{` `        ``if` `(s == -``1``) {` `            ``return``;` `        ``}` `        ``getEdges(p[s], edges, p);` `        ``edges.add(s);` `    ``}` `    ``// Calculate the shortest distance` `    ``// after removing an edge between` `    ``// v1 and v2` `    ``static` `void` `distHelper(List > graph,` `                           ``int``[] d, ``int` `v1, ``int` `v2, ``int` `n)` `    ``{` `        ``boolean``[] visited = ``new` `boolean``[n];` `        ``Queue<``int``[]> q = ``new` `LinkedList<>();` `        ``q.offer(``new` `int``[] { ``0``, ``0` `});` `        ``visited[``0``] = ``true``;` `        ``while` `(!q.isEmpty()) {` `            ``int``[] a = q.poll();` `            ``for` `(``int` `i : graph.get(a[``0``])) {` `                ``if` `((i == v1 && a[``0``] == v2)` `                    ``|| (i == v2 && a[``0``] == v1)) {` `                    ``continue``;` `                ``}` `                ``if` `(!visited[i]) {` `                    ``d[i] = ``1` `+ a[``1``];` `                    ``visited[i] = ``true``;` `                    ``q.offer(``new` `int``[] { i, d[i] });` `                ``}` `            ``}` `        ``}` `    ``}` `    ``// Calculates the shortest distances and` `    ``// maintain a parent array`   `    ``static` `void` `dist(List > graph, ``int``[] d,` `                     ``int``[] p, ``int` `n)` `    ``{ ``// Vector to mark the nodes visited` `        ``boolean``[] visited = ``new` `boolean``[n];`   `        ``// For BFS` `        ``Queue<``int``[]> q = ``new` `LinkedList<>();` `        ``q.offer(``new` `int``[] { ``0``, ``0` `});` `        ``visited[``0``] = ``true``;` `        ``while` `(!q.isEmpty()) {` `            ``int``[] a = q.poll();` `            ``for` `(``int` `i : graph.get(a[``0``])) {` `                ``if` `(!visited[i]) {` `                    ``p[i] = a[``0``];` `                    ``d[i] = ``1` `+ a[``1``];` `                    ``visited[i] = ``true``;` `                    ``q.offer(``new` `int``[] { i, d[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 > graph = ``new` `ArrayList<>();` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``graph.add(``new` `ArrayList<>());` `        ``}` `        ``for` `(``int` `i = ``0``; i < m; i++) {` `            ``int` `a = arr[i][``0``] - ``1``;` `            ``int` `b = arr[i][``1``] - ``1``;` `            ``graph.get(a).add(b);` `            ``graph.get(b).add(a);` `        ``}` `        ``// Initializing the arrays` `        ``int``[] p = ``new` `int``[n];` `        ``Arrays.fill(p, -``1``);` `        ``int``[] d = ``new` `int``[n];` `        ``Arrays.fill(d, Integer.MAX_VALUE);` `        ``// Calculate the shortest path` `        ``dist(graph, d, p, n);` `        ``// Vector to store the lengths` `        ``// of possible paths` `        ``List distances = ``new` `ArrayList<>();` `        ``distances.add(d[n - ``1``]);` `        ``List edges = ``new` `ArrayList<>();` `        ``// Get all the edges along the shortest path` `        ``getEdges(n - ``1``, edges, p);` `        ``// Iterate over the range` `        ``for` `(``int` `i = ``0``; i + ``1` `< edges.size(); i++) {` `            ``// Calculate shortest distance after` `            ``// removing the edge` `            ``distHelper(graph, d, edges.get(i),` `                       ``edges.get(i + ``1``), n);` `            ``distances.add(d[n - ``1``]);` `        ``}` `        ``// Sort the paths in ascending order`   `        ``Collections.sort(distances);` `        ``if` `(distances.size() == ``1``) {` `            ``System.out.println(``0``);` `        ``}` `        ``else` `{` `            ``System.out.println(distances.get(``1``)` `                               ``- distances.get(``0``));` `        ``}` `    ``}` `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int` `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);` `    ``}` `}`

## Python3

 `# Python3 program for the above approach`   `edges, d, p ``=` `[], [], []`   `# Function to get all the edges in` `# the shortest path` `def` `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 v2` `def` `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 array` `def` `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 path` `def` `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#

 `// C# program for the above approach` `using` `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> 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> q = ``new` `List>();` `        ``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> 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> q = ``new` `List>();` `        ``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> graph = ``new` `List>();` `        ``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.`

## Javascript

 ``

Output

```1
```

Time Complexity: O(N*M)
Auxiliary Space: O(N)

Previous
Next