问题
Running the Depth First Search (DFS) algorithm over a given graph G = (V,E)
which is connected and undirected provides a spanning tree. While running DFS on the graph, when we arrive to a vertex which it's degree is greater than 1 , i.e - there is more than one edge connected to it , we randomly choose an edge to continue with. I'd like to know if the option to choose an edge (or a vertex) to continue with actually allows as to create every spanning tree of a given graph using DFS?
回答1:
Since you mentioned in the comments that given a spanning tree you want some DFS that outputs the same tree, This shouldn't be a problem.
Suppose you have the required spanning tree and the graph in the form of an adjacency list and have a method edge_exists(u,v) which returns true or false depending on whether the edge is present or not in the given spanning tree.
explore(node):
visited[node] = 1;
for v in node.neighbors:
if edge_exists(node, v) && !visited[v]:
v.p = node
explore(v)
BTW i don't think you need to do a visited count since you have a spanning tree, so edge_exisits will do roughly the same for you
By programmatically outputting the spanning tree, I meant, given a graph output all the spanning trees. I am not sure how to do this.
回答2:
Is your question "can i find all spanning trees in a graph using DFS?"
Then the answer is no my friend. The state of DFS algorithm at any point of time is like a train, where coaches are linked one after the other. You traverse the chain. To find a spanning tree you will have to travel to a depth, D where
D = N,number of vertices in the graph.
To reach a state where the above condition meets you will have to traverse such that
v1->v2->v3->v4.....vn-1 -> vn
Where the numbers represent the traversal history and
vi != vj where i,j ∈ {1...n}. & i != j
So, if there exists a spanning tree such that v1->v3->v4 ... and v1->v2 as well DFS approach fails to produce that result.
In short you will not be able to find any spanning trees where even 1 vertice is pasrt of more than 1 edges.
来源:https://stackoverflow.com/questions/17601781/create-spanning-tree-with-dfs