3

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?

Stephan
  • 16,509
  • 7
  • 35
  • 61
  • 1
    I think yes. Start with a spanning tree of a graph, I think you can find a Depth First Traversal that fits it? – sukunrt Jul 11 '13 at 19:32
  • @sukunrt , i've also thought about it , but I'm afraid there are some cases I don't consider –  Jul 11 '13 at 20:35
  • I think if you're considering random(arbitrary) selection of edges it's possible to generate any spanning tree, but outputting all spanning programmatically would be difficult. – sukunrt Jul 11 '13 at 20:44
  • @sukunrt , what do you mean be outputting programmatically ? I'll rephrase my original question - given a spanning tree of G, could it be provided by running DFS from any vertex in the graph ? thanks –  Jul 11 '13 at 21:00

2 Answers2

2

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.

sukunrt
  • 1,523
  • 10
  • 20
0

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.