Length of the longest path ending at vertex V in a Graph | Javascript program for the above approach ; Function to perform DFS Traversal from source node to the deepest node and update maximum distance to the deepest node ; Mark source as visited ; Update the maximum distance ; Traverse the adjacency list of the current source node ; Recursively call for the child node ; Backtracking step ; Function to calculate maximum length of the path ending at vertex v from any source node ; Stores the maximum length of the path ending at vertex v ; Stores the size of the matrix ; Stores the adjacency list of the given graph ; Traverse the matrix to create adjacency list ; Perform DFS Traversal to update the maximum distance ; Driver code
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 ) ) ;