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.

ApplicationsDFSBFS
Spanning forest, connected components, paths, cyclesVV
shortest pathsV
Biconnected componentsV
  • 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)
dfs
  • 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
bfs