Breadth-First Search and Depth-First Search in Java

I decided to implement Breadth First Search and Depth First Search in Java. The implementation uses a Directed as the underlying abstract data type, keeps track of visited graph nodes by keeping a separate data structure, and implements BFS by using a Queue.

Some implementations only implement DFS and BFS on trees, but this implementation uses a graph because a tree is really a directed graph with no cycles (i.e. a node cannot reach itself in traversal). However, in the case of a graph, when a node can reach itself, you have to pay special attention to those loops by marking nodes as “visited” so that you don’t “visit” them again and end up in a stack overflow or an infinite loop. There is more than one way to do this: by keeping a separate data structure of the visited nodes (the way I did it) or by adding an extra field to each node, mark it as visited each time it is visited, and reset it once you are done with the search. Since both methods would take linear time but resetting the nodes’ visited flags would make coding more complicated, I chose to keep a separate data structure for that.

Source

UPDATE 2012/10/16: Graph in PHP. Interestingly, PHP arrays use hash maps as the underlying structure, so using key/value pairs might actually speed up the algorithm.

Leave a Reply