Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the good of using 3 states for a vertex in DFS?

In the explanation of depth-first search (DFS) in Algorithms in a Nutshell (2nd edition), the author used 3 states for a vertex, say white(not visited), gray(has unvisited neighbors), black(visited).

enter image description here

Two states (white and black) are enough for a traverse. Why add the gray state? What's it used for?

like image 666
nn0p Avatar asked Aug 13 '16 16:08

nn0p


People also ask

Does DFS visit every vertex?

DFS Properties: DFS(u) reaches all vertices reachable from u. On undirected graphs, DFS(u) visits all vertices in CC(u), and the DFS-tree obtained is a spanning tree of G.

How does DFS works in search of nodes or vertices?

Depth First Search ExampleWe start from vertex 0, the DFS algorithm starts by putting it in the Visited list and putting all its adjacent vertices in the stack. Next, we visit the element at the top of stack i.e. 1 and go to its adjacent nodes. Since 0 has already been visited, we visit 2 instead.

What is a DFS useful for in a graph?

In theoretical computer science, DFS is typically used to traverse an entire graph, and takes time , where is the number of vertices and the number of edges. This is linear in the size of the graph. In these applications it also uses space.


2 Answers

This is a variation of the DFS algorithm shown in Introduction to Algorithms by Coerman at al.

When you use 3 colors instead of only 2, it gives you more information. Fist, it allows you at each point during the algorithm run, to know which vertices are currently "open" (gray), which are "closed" (black) and which are unexplored yet (white).

In addition, when you use "timestamping" of the colorings (which is a list saying when you color each vertex in the order it occurd) of DFS using 3 colors - you can find out interesting properties about the graph, like backedges. This is used for example to determine if a graph is acyclic or not.

Note that for the sole purpose of discovering a graph - the 3 colors are indeed not mandatory, and indeed exercise 22-3.4 asks you to show that.

like image 168
amit Avatar answered Sep 22 '22 14:09

amit


You are correct.

Instead of coloring a vertex gray, you can color it black, and the algorithm still works.

It is easy to see that because nowhere in the code the colors gray and black are being checked. The only check is whether a vertex is white or not (the line marked as 2). This means all the colors which aren't white are equivalent.

I'm guessing the point of using a third color here is for verbosity and/or visualization purposes. If you were to display the graph while traversing it, the third color makes it much clearer what the status of the traversal process is, i.e. which nodes are currently "being visited".

like image 37
shx2 Avatar answered Sep 21 '22 14:09

shx2