- Published on
DFS vs. BFS
DFS(Depth First Search) and BFS(Breadth First Search) are algorithms used to traverse
graphs or trees. However, they differ in the way they explore the graph and the order in which they visit nodes.
Applications | DFS | BFS |
---|---|---|
Spanning forest, connected components, paths, cycles | V | V |
shortest paths | V | |
Biconnected components | V |
Depth First Search
- For a graph with n nodes and m edges, the time complexity is
O(m+n)
- Use a
stack
to store nodes; stacks are LIFO (last-in, first-out)
Breadth First Search
- For a graph with n nodes and m edges, the time complexity is
O(m+n)
- Use a
queue
to store nodes. Queues are FIFO - If the graph is unweighted, use BFS to obtain the
shortest path