Wouldn't it keep finding t if we start at s?
Give a linear-time algorithm that takes as input a directed acyclic graph G = (V,E) and two vertices s and t, and returns the number of paths from s to t in G.
solution:
The basic idea here is to start at vertex t, and use depth-first search in reverse direction until we reach vertex s. Each and maintains a counter which indicates the number of unique reverse paths found from vertex t.
- Initialize counters to 0 for all vertices.
- Start depth-first-search in reverse direction using vertex t as a root.
- For each edge (u, y) examined in the breadth-first search.
Counter(v) = max{ Counter(v) + 1, Counter(v) + Counter(u) }
- Return Counter(s).
Counter(s)
being 1 (or 0). – svick