Skip to content
Related Articles

Related Articles

Length of the longest path ending at vertex V in a Graph

View Discussion
Improve Article
Save Article
Like Article
  • 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++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to perform DFS Traversal from
// source node to the deepest node and
// update maximum distance to the deepest node
void dfs(int src, vector<int> Adj[],
         vector<bool>& visited, int level,
         int& distance)
{
 
    // Mark source as visited
    visited[src] = true;
 
    // Update the maximum distance
    distance = max(distance, level);
 
    // Traverse the adjacency list
    // of the current source node
    for (auto& child : Adj[src]) {
 
        // Recursively call
        // for the child node
        if (child != src
            and visited[child] == false) {
            dfs(child, Adj, visited,
                level + 1, distance);
        }
    }
 
    // Backtracking step
    visited[src] = false;
}
 
// Function to calculate maximum length
// of the path ending at vertex V from
// any source node
int maximumLength(vector<vector<int> >& mat,
                  int V)
{
 
    // Stores the maximum length of
    // the path ending at vertex V
    int distance = 0;
 
    // Stores the size of the matrix
    int N = (int)mat.size();
 
    // Stores the adjacency list
    // of the given graph
    vector<int> Adj[N];
 
    vector<bool> visited(N, false);
 
    // Traverse the matrix to
    // create adjacency list
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            if (mat[i][j] == 1) {
                Adj[i].push_back(j);
            }
        }
    }
 
    // Perform DFS Traversal to
    // update the maximum distance
    dfs(V, Adj, visited, 0, distance);
 
    return distance;
}
 
// Driver Code
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




// Java program for the above approach
import java.util.ArrayList;
 
class GFG{
     
static int distance;
 
// Function to perform DFS Traversal from source node to
// the deepest node and update maximum distance to the
// deepest node
private static void dfs(int src, ArrayList<ArrayList<Integer>> Adj,
                                 ArrayList<Boolean> visited, int level)
{
     
    // Mark source as visited
    visited.set(src, true);
 
    // Update the maximum distance
    distance = Math.max(distance, level);
 
    // Traverse the adjacency list of the current
    // source node
    for(int child : Adj.get(src))
    {
         
        // Recursively call for the child node
        if ((child != src) &&
            (visited.get(child) == false))
        {
            dfs(child, Adj, visited, level + 1);
        }
    }
     
    // Backtracking step
    visited.set(src, false);
}
 
// Function to calculate maximum length of the path
// ending at vertex v from any source node
private static int maximumLength(int[][] mat, int v)
{
     
    // Stores the maximum length of the path ending at
    // vertex v
    distance = 0;
 
    // Stores the size of the matrix
    int N = mat[0].length;
 
    ArrayList<Boolean> visited = new ArrayList<Boolean>();
 
    for(int i = 0; i < N; i++)
    {
        visited.add(false);
    }
 
    // Stores the adjacency list of the given graph
    ArrayList<
    ArrayList<Integer>> Adj = new ArrayList<
                                  ArrayList<Integer>>(N);
 
    for(int i = 0; i < N; i++)
    {
        Adj.add(new ArrayList<Integer>());
    }
 
    int i, j;
 
    // Traverse the matrix to create adjacency list
    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);
            }
        }
    }
     
    // Perform DFS Traversal to update
    // the maximum distance
    dfs(v, Adj, visited, 0);
    return distance;
}
 
// Driver code
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));
}
}
 
// This code is contributed by abhinavjain194

Python3




# Python3 program for the above approach
visited = [False for i in range(4)]
 
# Function to perform DFS Traversal from
# source node to the deepest node and
# update maximum distance to the deepest node
def dfs(src, Adj, level, distance):
     
    global visited
     
    # Mark source as visited
    visited[src] = True
 
    # Update the maximum distance
    distance = max(distance, level)
 
    # Traverse the adjacency list
    # of the current source node
    for child in Adj[src]:
         
        # Recursively call
        # for the child node
        if (child != src and visited[child] == False):
            dfs(child, Adj, level + 1, distance)
 
    # Backtracking step
    visited[src] = False
 
# Function to calculate maximum length
# of the path ending at vertex V from
# any source node
def maximumLength(mat, V):
     
    # Stores the maximum length of
    # the path ending at vertex V
    distance = 0
 
    # Stores the size of the matrix
    N = len(mat)
 
    # Stores the adjacency list
    # of the given graph
    Adj = [[] for i in range(N)]
 
    # Traverse the matrix to
    # create adjacency list
    for i in range(N):
        for j in range(N):
            if (mat[i][j] == 1):
                Adj[i].append(j)
 
    # Perform DFS Traversal to
    # update the maximum distance
    dfs(V, Adj, 0, distance)
 
    return distance + 2
 
# Driver Code
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))
 
# This code is contributed by ipg2016107

C#




// C# program for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG{
     
static int distance;
 
// Function to perform DFS Traversal from
// source node to the deepest node and
// update maximum distance to the deepest node
static void dfs(int src, List<List<int>> Adj,
                List<bool> visited, int level)
{
     
    // Mark source as visited
    visited[src] = true;
  
    // Update the maximum distance
    distance = Math.Max(distance, level);
  
    // Traverse the adjacency list of
    // the current source node
    foreach(int child in Adj[src])
    {
         
        // Recursively call for the child node
        if ((child != src) &&
            (visited[child] == false))
        {
            dfs(child, Adj, visited, level + 1);
        }
    }
      
    // Backtracking step
    visited[src] = false;
}
  
// Function to calculate maximum length of the path
// ending at vertex v from any source node
static int maximumLength(int[,] mat, int v)
{
     
    // Stores the maximum length of the path
    // ending at vertex v
    distance = 0;
  
    // Stores the size of the matrix
    int N = mat.GetLength(0);
  
    List<bool> visited = new List<bool>();
  
    for(int i = 0; i < N; i++)
    {
        visited.Add(false);
    }
  
    // Stores the adjacency list of the given graph
    List<List<int>> Adj = new List<List<int>>(N);
  
    for(int i = 0; i < N; i++)
    {
        Adj.Add(new List<int>());
    }
  
    // Traverse the matrix to create adjacency list
    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);
            }
        }
    }
     
    // Perform DFS Traversal to update
    // the maximum distance
    dfs(v, Adj, visited, 0);
    return distance;
}
 
// Driver code
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));
}
}
 
// This code is contributed by mukesh07

Javascript




<script>
// Javascript program for the above approach
     
var distance = 0;
 
// Function to perform DFS Traversal from source node to
// the deepest node and update maximum distance to the
// deepest node
function dfs(src, Adj, visited, level)
{
     
    // Mark source as visited
    visited[src] = true;
 
    // Update the maximum distance
    distance = Math.max(distance, level);
 
    // Traverse the adjacency list of the current
    // source node
    for(var child of Adj[src])
    {
         
        // Recursively call for the child node
        if ((child != src) &&
            (visited[child] == false))
        {
            dfs(child, Adj, visited, level + 1);
        }
    }
     
    // Backtracking step
    visited[src] = false;
}
 
// Function to calculate maximum length of the path
// ending at vertex v from any source node
function maximumLength(mat, v)
{
     
    // Stores the maximum length of the path ending at
    // vertex v
    distance = 0;
 
    // Stores the size of the matrix
    var N = mat[0].length;
 
    var visited = [];
 
    for(var i = 0; i < N; i++)
    {
        visited.push(false);
    }
 
    // Stores the adjacency list of the given graph
    var Adj = Array.from(Array(N), ()=>Array());
 
    var i, j;
 
    // Traverse the matrix to create adjacency list
    for(i = 0; i < mat[0].length; i++)
    {
        for(j = 0; j < mat.length; j++)
        {
            if (mat[i][j] == 1)
            {
                Adj[i].push(j);
            }
        }
    }
     
    // Perform DFS Traversal to update
    // the maximum distance
    dfs(v, Adj, visited, 0);
    return distance;
}
 
// Driver code
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));
 
// This code is contributed by rutvik_56.
</script>

Output: 

2

 

Time Complexity: O(N2)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!