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++
#include <bits/stdc++.h>
using namespace std;
void dfs(vector<vector< int > >& graph, int s, int e,
vector< int > v, int count, vector< int >& dp)
{
if (s == e) {
dp.push_back(count);
return ;
}
for ( auto i : graph[s]) {
if (v[i] != 1) {
v[i] = 1;
dfs(graph, i, e, v, count + 1, dp);
v[i] = 0;
}
}
}
void findDifference( int n, int m, int arr[][2])
{
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< int > v(n, 0);
vector< int > dp;
v[0] = 1;
dfs(graph, 0, n - 1, v, 0, dp);
sort(dp.begin(), dp.end());
if (dp.size() != 1)
cout << dp[1] - dp[0];
else
cout << 0;
}
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
import java.util.*;
public class Main
{
static void dfs(Vector<Vector<Integer>> graph, int s,
int e, int [] v, int count, Vector<Integer> dp) {
if (s == e)
{
dp.add(count);
return ;
}
for ( int i : graph.get(s)) {
if (v[i] != 1 )
{
v[i] = 1 ;
dfs(graph, i, e, v, count + 1 , dp);
v[i] = 0 ;
}
}
}
static void findDifference( int n, int m, int [][] arr)
{
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 );
}
int [] v = new int [n];
Arrays.fill(v, 0 );
Vector<Integer> dp = new Vector<Integer>();
v[ 0 ] = 1 ;
dfs(graph, 0 , n - 1 , v, 0 , dp);
Collections.sort(dp);
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);
}
}
|
Python3
def dfs(graph, s, e, v, count, dp):
if (s = = e):
dp.append(count)
return
for i in graph[s]:
if (v[i] ! = 1 ):
v[i] = 1
dfs(graph, i, e, v, count + 1 , dp)
v[i] = 0
def findDifference(n, m, arr):
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 )
v = [ 0 ] * (n)
dp = []
v[ 0 ] = 1
dfs(graph, 0 , n - 1 , v, 0 , dp)
dp.sort()
if ( len (dp) ! = 1 ):
print (dp[ 1 ] - dp[ 0 ], end = "")
else :
print ( 0 , end = "")
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)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void dfs(List<List< int >> graph, int s, int e, List< int > v, int count, List< int > dp) {
if (s == e)
{
dp.Add(count);
return ;
}
foreach ( int i in graph[s]) {
if (v[i] != 1)
{
v[i] = 1;
dfs(graph, i, e, v, count + 1, dp);
v[i] = 0;
}
}
}
static void findDifference( int n, int m, int [,] arr)
{
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);
}
List< int > v = new List< int >();
for ( int i = 0; i < n; i++)
{
v.Add(0);
}
List< int > dp = new List< int >();
v[0] = 1;
dfs(graph, 0, n - 1, v, 0, dp);
dp.Sort();
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);
}
}
|
Javascript
<script>
function dfs(graph, s, e, v, count, dp) {
if (s == e)
{
dp.push(count);
return ;
}
for (let i of graph[s]) {
if (v[i] != 1)
{
v[i] = 1;
dfs(graph, i, e, v, count + 1, dp);
v[i] = 0;
}
}
}
function findDifference(n, m, arr)
{
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);
}
let v = new Array(n).fill(0);
let dp = [];
v[0] = 1;
dfs(graph, 0, n - 1, v, 0, dp);
dp.sort((a, b) => a - b);
if (dp.length != 1) document.write(dp[1] - dp[0]);
else document.write(0);
}
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);
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
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);
}
void dist_helper(vector<vector< int > > graph, vector< int >& d,
int v1, int v2, int n)
{
vector< int > v(n, 0);
queue<pair< int , int > > q;
q.push(make_pair(0, 0));
v[0] = 1;
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]));
}
}
}
}
void dist(vector<vector< int > > graph, vector< int >& d,
vector< int >& p, int n)
{
vector< int > v(n, 0);
queue<pair< int , int > > q;
q.push(make_pair(0, 0));
v[0] = 1;
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]));
}
}
}
}
void findDifference( int n, int m, int arr[][2])
{
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< int > p(n, -1);
vector< int > d(n, 1e9);
dist(graph, d, p, n);
vector< int > distances;
distances.push_back(d[n - 1]);
vector< int > edges;
get_edges(n - 1, edges, p);
for ( int i = 0; i + 1 < edges.size(); i++) {
dist_helper(graph, d, edges[i], edges[i + 1], n);
distances.push_back(d[n - 1]);
}
sort(distances.begin(), distances.end());
if (distances.size() == 1)
cout << 0 << endl;
else
cout << distances[1] - distances[0] << endl;
}
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
import java.util.*;
class Main {
static void getEdges( int s, List<Integer> edges,
int [] p)
{
if (s == - 1 ) {
return ;
}
getEdges(p[s], edges, p);
edges.add(s);
}
static void distHelper(List<List<Integer> > 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] });
}
}
}
}
static void dist(List<List<Integer> > graph, int [] d,
int [] p, 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 (!visited[i]) {
p[i] = a[ 0 ];
d[i] = 1 + a[ 1 ];
visited[i] = true ;
q.offer( new int [] { i, d[i] });
}
}
}
}
static void findDifference( int n, int m, int [][] arr)
{
List<List<Integer> > 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);
}
int [] p = new int [n];
Arrays.fill(p, - 1 );
int [] d = new int [n];
Arrays.fill(d, Integer.MAX_VALUE);
dist(graph, d, p, n);
List<Integer> distances = new ArrayList<>();
distances.add(d[n - 1 ]);
List<Integer> edges = new ArrayList<>();
getEdges(n - 1 , edges, p);
for ( int i = 0 ; i + 1 < edges.size(); i++) {
distHelper(graph, d, edges.get(i),
edges.get(i + 1 ), n);
distances.add(d[n - 1 ]);
}
Collections.sort(distances);
if (distances.size() == 1 ) {
System.out.println( 0 );
}
else {
System.out.println(distances.get( 1 )
- distances.get( 0 ));
}
}
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
edges, d, p = [], [], []
def get_edges(s):
global edges, d, p
if s = = - 1 :
return
get_edges(p[s])
edges.append(s)
def dist_helper(graph, v1, v2, n):
global edges, d, p
v = [ 0 ] * (n)
q = []
q.append([ 0 , 0 ])
v[ 0 ] = 1
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]])
def dist(graph, n):
global edges, d, p
v = [ 0 ] * (n)
q = []
q.append([ 0 , 0 ])
v[ 0 ] = 1
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]])
def findDifference(n, m, arr):
global edges, d, p
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 )
p = [ - 1 ] * (n)
d = [ 1e9 ] * (n)
dist(graph, n)
distances = []
distances.append(d[n - 1 ])
edges = []
get_edges(n - 1 )
i = 0
while i + 1 < len (edges):
dist_helper(graph, edges[i], edges[i + 1 ], n)
distances.append(d[n - 1 ])
i + = 1
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)
|
C#
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 >();
static void get_edges( int s)
{
if (s == -1)
return ;
get_edges(p[s]);
edges.Add(s);
}
static void dist_helper(List<List< int >> graph, int v1, int v2, int n)
{
List< int > v = new List< int >();
for ( int i = 0; i < n; i++)
{
v.Add(0);
}
List<Tuple< int , int >> q = new List<Tuple< int , int >>();
q.Add( new Tuple< int , int >(0, 0));
v[0] = 1;
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]]));
}
}
}
}
static void dist(List<List< int >> graph, int n)
{
List< int > v = new List< int >();
for ( int i = 0; i < n; i++)
{
v.Add(0);
}
List<Tuple< int , int >> q = new List<Tuple< int , int >>();
q.Add( new Tuple< int , int >(0, 0));
v[0] = 1;
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]]));
}
}
}
}
static void findDifference( int n, int m, int [,] arr)
{
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);
}
for ( int i = 0; i < n; i++)
{
p.Add(-1);
d.Add(1000000000);
}
dist(graph, n);
List< int > distances = new List< int >();
distances.Add(d[n - 1]);
get_edges(n - 1);
for ( int i = 0; i + 1 < edges.Count; i++) {
dist_helper(graph, edges[i], edges[i + 1], n);
distances.Add(d[n - 1]);
}
distances.Sort();
if (distances.Count == 1)
{
Console.WriteLine(0);
}
else
{
Console.WriteLine((distances[1] - distances[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);
}
}
|
Javascript
<script>
let edges = [], d = [], p = [];
function get_edges(s)
{
if (s == -1)
return ;
get_edges(p[s]);
edges.push(s);
}
function dist_helper(graph, v1, v2, n)
{
let v = [];
for (let i = 0; i < n; i++)
{
v.push(0);
}
let q = [];
q.push([0, 0]);
v[0] = 1;
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]]]);
}
}
}
}
function dist(graph, n)
{
let v = [];
for (let i = 0; i < n; i++)
{
v.push(0);
}
let q = [];
q.push([0, 0]);
v[0] = 1;
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 findDifference(n, m, arr)
{
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);
}
for (let i = 0; i < n; i++)
{
p.push(-1);
d.push(1e9);
}
dist(graph, n);
let distances = [];
distances.push(d[n - 1]);
get_edges(n - 1);
for (let i = 0; i + 1 < edges.length; i++) {
dist_helper(graph, edges[i], edges[i + 1], n);
distances.push(d[n - 1]);
}
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);
</script>
|
Time Complexity: O(N*M) Auxiliary Space: O(N)
|