I have to write an algorithm that find the path in DAG with single source and single sink…
I really don’t know what to do ( tried to use DSF and topological sort but nothing…)
I don’t want anyone to solve it for me but just some guidance.
Thank you
BFS finds shortest path in general unweighted graph – and also specifically in DAG [since it is also a graph]. It is also pretty simple to code it.
Note that DFS will find a path – but it doesn’t have to be the shortest one.
You might also want to have a look at this post to see how to get the actual path from BFS after running it.
EDIT: according to your comments, it seems you want
O(|V|)solution, and it doesn’t have to be shortest. a modification of DFS is the way to do then, since the DAG has a single source and a single sink, every path from the source reaches the sink.Note that since your graph is a DAG and since we established that every path from the source reaches the sink, you don’t need to go backward after exploring a certain path [so no recursion or stack is needed].
pseudo-code:
after running this algorithm, you need to follow back the map from the target to the
source – and you get the actual path [reversed of course]
The complexity is indeed
O(n)because we visit each node at most once. In order to maintainO(n)the map has to be a hashmap [and not a treemap]. If the vertices are enumerated – you can even implement the map as an array.