BFS and DFS
BFS and DFS
of a graph in a breadthwise order. It means it starts at a given vertex or node and visits all the
vertices at the same level before moving to the next level. It is a recursive algorithm for
searching all the vertices of a graph or tree data structure.
BFS Algorithm
For the BFS implementation, we will categorize each vertex of the graph into two categories:
Visited
Not Visited
The reason for this division is to prevent the traversal of the same node again thus avoiding
cycles in the graph.
Breadth First Traversal in Data Structure uses a queue to keep track of the vertices to visit.
BFS algorithm works:
create a queue Q
mark v as visited and put v into Q
while Q is non-empty
remove the head u of Q
mark and enqueue all (unvisited)
neighbours of u
DFS: The depth-first search algorithm works by starting from an arbitrary node of the graph
and exploring as far as possible before backtracking i.e. moving to an adjacent node until
there is no unvisited adjacent node. After backtracking, it repeats the same process for all the
remaining vertices which have not been visited till now. It is a recursive algorithm for
searching all the vertices of a graph or tree data structure.
DFS Algorithm
For the DFS implementation, we will categorize each vertex of the graph into two categories:
Visited
Not Visited
The reason for this division is to prevent the traversal of the same node again thus, avoiding
cycles in the graph. Depth First Traversal in Data Structure uses a stack to keep track of the
vertices to visit. A boolean visited array is used to mark the visited vertices.
DFS algorithm
1. Start by selecting a starting vertex or node.
2. Add the starting vertex on top of a stack.
3. Take the top item of the stack and add it to the visited list/array.
4. Create a list of that vertex's adjacent nodes. Add the ones that aren't in the visited list
to the top of the stack.
Keep repeating steps 3 and 4 until the stack is empty.