Question

I need pseudocode based on the depth-first search to find the longest path in a DAG,...

I need pseudocode based on the depth-first search to find the longest path in a DAG, assuming all edges have the same weight.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Pseudo Code:

/* We will use dynamic programming using dfs. Let dp[node] be the longest path distance from node
@params:
int node: current node
vector<int> adj[]: Adjacency list of graph
int dp[]: array to store longest path distance
bool vis[]: visited array*/

void dfs(node,adj,dp,vis):
START
vis[node] <- true //mark node as visited
for i = 0 to adj[node].size():
v <- adj[node][i] //neighbour node
if(vis[v]=false):
dfs(v, adj, dp, vis)
if(1 + dp[v]>dp[node]):
dp[node] <- 1 + dp[v]
END
  
/*@params
vector<int> adj[]: Adjacency list of graph
int n: number of nodes
int wt = weight of each edge*/
  
void findLongestPath(vector<int> adj[], int n, int wt):
START
   // Dp array initialized to 0
   dp[n + 1] <- {0}
// visited array initialized to false
   vis[n + 1] <- {false}
   for i = 1 to n+1:
       if (vis[i]=false) :
           dfs(i, adj, dp, vis);
   ans //to store number of edges in longest path
   max //to store the vertex from which the longest path will start
   // find the maximum of all dp[i]
   for i = 1 to n+1:
       if(dp[i]>ans):
       ans = dp[i]
       max = i
  
   print "The longest path contain "+ans+" edges. It syarts from node "+max+". Total cost: "+ans*wt
END

Add a comment
Know the answer?
Add Answer to:
I need pseudocode based on the depth-first search to find the longest path in a DAG,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT