Finding cycles with a stack-based depth first search

I know that you use a recursive implementation of DFS where all nodes start as white, are colored gray when they are first encountered, and are colored black after all of their children are explored, you know that there is a cycle if you ever encounter a gray node.

But how do you do this with a stack implementation?


This answer on Stackoverflow is pointing to a Java code sample implementing DFS with stack.

Besides, if you feel comfortable with C and I hope you like chess as me too, I strongly advise you to study Andy DuPlain's fbk2rbm's source code released in the public domain.

It's a handy utility to convert Fritz power-books to Rebel 7 format (Opening libraries in the chess parlance).

It makes use of stack, chess move beeing seen as node.

Excerpt :


/* Used to hold move */
struct Move {
  char FromFile, FromRank;
  char ToFile, ToRank;
  unsigned char Eval;
  char StartVar;    

/* List of moves seen */
struct Move Moves[256]; 


Extending the program to address position cylcing detection (given that different move sequences may lead to the same position / collision) would be an excellent exercise related to your question.

Need Your Help

Rails not using digested assets in production

ruby-on-rails ruby-on-rails-4 asset-pipeline

I have a Rails 4.2 app which is running with precompiled assets on Heroku. We are trying to move to new platform (Aptible), but using the same settings, our app does not get the assets correctly a...