Reputation: 4040
My question isn't really about the mechanism of either search type. I feel it's a lot more mundane than that - I don't understand the input and output of either. More specifically, in CLRS, BFS takes as input a graph and a source node, but DFS takes only a graph. Does DFS not care where you search from then?
So that's the input confusion. The output confusion is that in DFS, when you're done you have a table-like structure recording each node's discovery and finish time, right? How do you extract a solution, i.e. a path from source to destination nodes, from that?
I hope I'm making sense. Thanks!
Edit: here's what I mean by DFS not taking a source node. This is the DFS pseudocode from CLRS. I don't see it taking a source node anywhere. All I see it doing is going through ALL the nodes in the graph.
DFS(G)
1 for each vertex u ∈ V[G]
2 do color[u] ← WHITE
3 π[u]← NIL
4 time ← 0
5 for each vertex u ∈ V[G]
6 do if color[u] = WHITE
7 then DFS-VISIT(u)
DFS-VISIT(u)
1 color[u] ← GRAY ✄ White vertex u has just been discovered.
2 time ← time+1
3 d[u] ← time
4 for each v ∈ Adj[u] ✄ Explore edge (u,v).
5 do if color[v] = WHITE
6 then π[v] ← u
7 DFS-VISIT(v)
8 color[u] ← BLACK ✄ Blacken u;it is finished.
9 f [u] ← time ← time+1
Upvotes: 1
Views: 2433
Reputation: 8361
The input confusion:
The particular DFS given by CLRS does not care about where you search from. The exact result of the search will depend on the ordering of the nodes in V[G]
. Normally I would think of DFS as starting from a node, e.g.:
DFS-Simple(G, s)
1 for each vertex u ∈ V[G]
2 do color[u] ← WHITE
3 π[u]← NIL
4 time ← 0
5 DFS-VISIT(s)
The version of CLRS produces a forest (one tree for each component of the graph) instead of just a single tree, which presumably suited their purpose better.
The output confusion:
The paths are recorded not by the time stamps, but by the parent pointers π
. For example given a node v
, you can print the path to its root node like this:
Print-Path-To-Root(v)
1 while v ≠ Nil
2 do print v
3 v ← π[v]
Upvotes: 1
Reputation: 7892
Both BFS and DFS take as input a source node.
When doing pathfinding with DFS, you simply stop when you find your node, and then work up the stack all the way to the original node to find the path.
Upvotes: 0