Length of the longest path ending at vertex V in a Graph
Last Updated :
27 Sep, 2021
Given a binary matrix mat[][] that represents the adjacency matrix representation of a graph, where mat[i][j] as 1 represents that there is an edge between vertices i and j and a vertex V, the task is to find the longest path from any node to the vertex X such that every vertex in the path occurs only once.
Examples:
Input: graph[][] = {{0, 1, 0, 0}, {1, 0, 1, 1}, {0, 1, 0, 0}, {0, 1, 0, 0}}, V = 2
Output: 2
Explanation:
The given graph is as follows:
0
|
1
/ \
2 3
The longest path ending at vertex 2 is 3 -> 1 -> 2. Therefore, the length of this path is 2.
Input: graph[][] = {{0, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 0}, {1, 0, 0, 0}}, V = 1
Output: 2
Approach: The given problem can be solved by performing DFS Traversal on the given graph from the source node as V and finding the maximum length of the path having the deepest node from the node V.
Follow the steps below to solve the problem:
- Initialize an adjacency list, say Adj[], from the given Graph representation in the matrix mat[][].
- Initialize an auxiliary vector, say visited[], to keep track of whether any vertex is visited or not.
- Initialize a variable, say distance as 0, to store the maximum length of the resultant path from any source node to the given vertex V.
- Perform DFS Traversal on the given graph from the node V and perform the following steps:
- Mark the current node V as visited, i.e., visited[V] = true.
- Update the value of distance to the maximum of distance and level.
- Traverse the adjacency list of the current source node V. If the child node is not same as the parent node and is not visited yet, then recursively perform DFS Traversal as dfs(child, Adj, visited, level + 1, distance).
- After completing the above steps, mark the current node V as unvisited to include the path if the cycle exists in the given graph.
- After completing the above steps, print the value of distance as the resultant maximum distance between any source node the given node V.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void dfs( int src, vector< int > Adj[],
vector< bool >& visited, int level,
int & distance)
{
visited[src] = true ;
distance = max(distance, level);
for ( auto & child : Adj[src]) {
if (child != src
and visited[child] == false ) {
dfs(child, Adj, visited,
level + 1, distance);
}
}
visited[src] = false ;
}
int maximumLength(vector<vector< int > >& mat,
int V)
{
int distance = 0;
int N = ( int )mat.size();
vector< int > Adj[N];
vector< bool > visited(N, false );
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++) {
if (mat[i][j] == 1) {
Adj[i].push_back(j);
}
}
}
dfs(V, Adj, visited, 0, distance);
return distance;
}
int main()
{
vector<vector< int > > mat = { { 0, 1, 0, 0 },
{ 1, 0, 1, 1 },
{ 0, 1, 0, 0 },
{ 0, 1, 0, 0 } };
int V = 2;
cout << maximumLength(mat, V);
return 0;
}
|
Java
import java.util.ArrayList;
class GFG{
static int distance;
private static void dfs( int src, ArrayList<ArrayList<Integer>> Adj,
ArrayList<Boolean> visited, int level)
{
visited.set(src, true );
distance = Math.max(distance, level);
for ( int child : Adj.get(src))
{
if ((child != src) &&
(visited.get(child) == false ))
{
dfs(child, Adj, visited, level + 1 );
}
}
visited.set(src, false );
}
private static int maximumLength( int [][] mat, int v)
{
distance = 0 ;
int N = mat[ 0 ].length;
ArrayList<Boolean> visited = new ArrayList<Boolean>();
for ( int i = 0 ; i < N; i++)
{
visited.add( false );
}
ArrayList<
ArrayList<Integer>> Adj = new ArrayList<
ArrayList<Integer>>(N);
for ( int i = 0 ; i < N; i++)
{
Adj.add( new ArrayList<Integer>());
}
int i, j;
for (i = 0 ; i < mat[ 0 ].length; i++)
{
for (j = 0 ; j < mat.length; j++)
{
if (mat[i][j] == 1 )
{
Adj.get(i).add(j);
}
}
}
dfs(v, Adj, visited, 0 );
return distance;
}
public static void main(String[] args)
{
int [][] mat = { { 0 , 1 , 0 , 0 },
{ 1 , 0 , 1 , 1 },
{ 0 , 1 , 0 , 0 },
{ 0 , 1 , 0 , 0 } };
int v = 2 ;
System.out.print(maximumLength(mat, v));
}
}
|
Python3
visited = [ False for i in range ( 4 )]
def dfs(src, Adj, level, distance):
global visited
visited[src] = True
distance = max (distance, level)
for child in Adj[src]:
if (child ! = src and visited[child] = = False ):
dfs(child, Adj, level + 1 , distance)
visited[src] = False
def maximumLength(mat, V):
distance = 0
N = len (mat)
Adj = [[] for i in range (N)]
for i in range (N):
for j in range (N):
if (mat[i][j] = = 1 ):
Adj[i].append(j)
dfs(V, Adj, 0 , distance)
return distance + 2
if __name__ = = '__main__' :
mat = [ [ 0 , 1 , 0 , 0 ],
[ 1 , 0 , 1 , 1 ],
[ 0 , 1 , 0 , 0 ],
[ 0 , 1 , 0 , 0 ] ]
V = 2
print (maximumLength(mat, V))
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
static int distance;
static void dfs( int src, List<List< int >> Adj,
List< bool > visited, int level)
{
visited[src] = true ;
distance = Math.Max(distance, level);
foreach ( int child in Adj[src])
{
if ((child != src) &&
(visited[child] == false ))
{
dfs(child, Adj, visited, level + 1);
}
}
visited[src] = false ;
}
static int maximumLength( int [,] mat, int v)
{
distance = 0;
int N = mat.GetLength(0);
List< bool > visited = new List< bool >();
for ( int i = 0; i < N; i++)
{
visited.Add( false );
}
List<List< int >> Adj = new List<List< int >>(N);
for ( int i = 0; i < N; i++)
{
Adj.Add( new List< int >());
}
for ( int i = 0; i < mat.GetLength(0); i++)
{
for ( int j = 0; j < mat.GetLength(0); j++)
{
if (mat[i, j] == 1)
{
Adj[i].Add(j);
}
}
}
dfs(v, Adj, visited, 0);
return distance;
}
static void Main()
{
int [,] mat = { { 0, 1, 0, 0 },
{ 1, 0, 1, 1 },
{ 0, 1, 0, 0 },
{ 0, 1, 0, 0 } };
int v = 2;
Console.Write(maximumLength(mat, v));
}
}
|
Javascript
<script>
var distance = 0;
function dfs(src, Adj, visited, level)
{
visited[src] = true ;
distance = Math.max(distance, level);
for ( var child of Adj[src])
{
if ((child != src) &&
(visited[child] == false ))
{
dfs(child, Adj, visited, level + 1);
}
}
visited[src] = false ;
}
function maximumLength(mat, v)
{
distance = 0;
var N = mat[0].length;
var visited = [];
for ( var i = 0; i < N; i++)
{
visited.push( false );
}
var Adj = Array.from(Array(N), ()=>Array());
var i, j;
for (i = 0; i < mat[0].length; i++)
{
for (j = 0; j < mat.length; j++)
{
if (mat[i][j] == 1)
{
Adj[i].push(j);
}
}
}
dfs(v, Adj, visited, 0);
return distance;
}
var mat = [ [ 0, 1, 0, 0 ],
[ 1, 0, 1, 1 ],
[ 0, 1, 0, 0 ],
[ 0, 1, 0, 0 ] ];
var v = 2;
document.write(maximumLength(mat, v));
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...