- Simple implementation of BFS & DFS in Java using Adjacency List for Graph Representation
- Uses almost identical code for BFS & DFS. BFS uses a LIFO Queue (LinkedList) while DFS uses a FIFO Queue (Stack)
- You can pick any node in the graph & run DFS or BFS from that node
- Ability to repeat & choose a different node or algorithm
- Constructor automatically creates a graph like this:
- CODE IS IDENTICAL! The only difference between BFS & DFS is the type of Queue
BFS usesLinkedList
(LIFO) while DFS usesStack
(FIFO)
Some code specific details:- BFS:
Queue<Integer> nodeQueue = new LinkedList<Integer>();
vs DFS:Stack<Integer> nodeQueue = new Stack<Integer>();
- BFS:
int nodeRemovedFromQueue = nodeQueue.remove();
vs DFS:int nodeRemovedFromQueue = nodeQueue.pop();
remove()
vspop()
- BFS:
- I used a
while loop
and aniterator
instead of an inner for loop since I'm usingLinkList
for each row in the Adjacency List - Calling either method will print the nodes in the order visited by the algorithm
- Uses a different approach for Breadth first search to display the actual layers as BFS ripples outward
- The line
layers.add(new ArrayList<Integer>());
create empty layer each iteration, but results in an extra layer when algorithm terminate.- This extra layer is ignored in
printBfsLayers()
if(!layers.get(i).isEmpty()){
System.out.print("Layer "+i+": ");
}
- This extra layer is ignored in