Calculate number of nodes between two vertices in an acyclic Graph by DFS method | Function to return the count of nodes in the path from source to destination ; Mark the node visited ; If dest is reached ; Traverse all adjacent nodes ; If not already visited ; If there is path , then include the current node ; Return 0 if there is no path between src and dest through the current node ; Function to return the count of nodes between two given vertices of the acyclic Graph ; Initialize an adjacency list ; Populate the edges in the list ; Mark all the nodes as not visited ; Count nodes in the path from src to dest ; Return the nodes between src and dest ; Given number of vertices and edges ; Given source and destination vertices ; Given edges
function dfs ( src , dest , vis , adj ) { vis [ src ] = 1 ; if ( src == dest ) { return 1 ; } for ( let u = 0 ; u < adj [ src ] . length ; u ++ ) { if ( vis [ adj [ src ] [ u ] ] == 0 ) { let temp = dfs ( adj [ src ] [ u ] , dest , vis , adj ) ; if ( temp != 0 ) { return temp + 1 ; } } } return 0 ; } function countNodes ( V , E , src , dest , edges ) { let adj = new Array ( V + 1 ) ; for ( let i = 0 ; i < adj . length ; i ++ ) adj [ i ] = [ ] ; for ( let i = 0 ; i < E ; i ++ ) { adj [ edges [ i ] [ 0 ] ] . push ( edges [ i ] [ 1 ] ) ; adj [ edges [ i ] [ 1 ] ] . push ( edges [ i ] [ 0 ] ) ; } let vis = new Array ( V + 1 ) ; for ( let i = 0 ; i < vis . length ; i ++ ) { vis [ i ] = 0 ; } let count = dfs ( src , dest , vis , adj ) ; return count - 2 ; } let V = 8 , E = 7 ; let src = 5 , dest = 2 ; let edges = [ [ 1 , 4 ] , [ 4 , 5 ] , [ 4 , 2 ] , [ 2 , 6 ] , [ 6 , 3 ] , [ 2 , 7 ] , [ 3 , 8 ] ] ; document . write ( countNodes ( V , E , src , dest , edges ) ) ;