8

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?

Saeid
  • 4,147
  • 7
  • 27
  • 43
nn0p
  • 1,189
  • 12
  • 28
  • Though not directly related to the DFS, but the third state, black, would be useful in finding cycle in a directed graph. An edge from Gray (in-progress) to Black (completed) should not be considered while detecting cycle. – ashish Aug 17 '23 at 10:47

2 Answers2

2

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.

amit
  • 175,853
  • 27
  • 231
  • 333
1

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".

shx2
  • 61,779
  • 13
  • 130
  • 153
  • 1
    While technically correct, I do not like this answer because it ignores (or fails to acknowledge) the context. The 3 colors system for DFS is well known, and is used with combination of timestamping the colorings to discover intereseting properties about a graph. – amit Aug 13 '16 at 19:36