wasAsked.

What is the difference between BFS and DFS?

Frequently Asked (All Companies) · Role not specified · coding

Published

Year not specified · Data Structures & Algorithms

Community answers

Posted by wasAsked editorial collection

Breadth-First Search (BFS) and Depth-First Search (DFS) are the two fundamental ways to traverse graphs and trees. They differ in the order nodes are visited and the data structure they use. BFS — Breadth-First Search - Visits nodes level by level: first all neighbours of the start node, then their neighbours, and so on. - Uses a queue (FIFO). - Finds the shortest path (fewest edges) in an unweighted graph. List<int> Bfs(Dictionary<int, List<int>> graph, int start) { var visited = new HashSet<int> { start }; var queue = new Queue<int>([start]); var order = new List<int>(); while (queue.Count > 0) { var node = queue.Dequeue(); order.Add(node); foreach (var next in graph[node]) if (visited.Add(next)) queue.Enqueue(next); // mark when enqueued to avoid duplicates } return order; } DFS — Depth-First Search - Goes as deep as possible along one path before backtracking. - Uses a stack — either explicitly or through recursion (the call stack). void Dfs(Dictionary<int, List<int>> graph, int node, HashSet<int> visited, List<int> order) { if (!visited.Add(node)) return; order.Add(node); foreach (var next in graph[node]) Dfs(graph, next, visited, order); } Example graph: 1 connects to 2 and 3; 2 connects to 4 and 5; 3 connects to 6. - BFS from 1: 1, 2, 3, 4, 5, 6 (level by level). - DFS from 1: 1, 2, 4, 5, 3, 6 (deep first). Complexity - Both run in O(V + E) time for adjacency lists (V vertices, E edges). - Space: BFS stores a whole frontier level in the queue — up to O(V), large for wide graphs. DFS stores the current path — O(depth), which can be O(V) for long chains; deep recursion can overflow the stack, so very deep graphs use an iterative DFS with an explicit stack. When to use BFS - Shortest path in unweighted graphs (minimum moves in a maze, degrees of separation in a social network, fewest hops in a network). - Level-order traversal of a tree. - Finding all nodes within k steps. - Web crawlers that explore nearby pages first. - Multi-source problems (for example "rotting oranges" or nearest exit from all cells). When to use DFS - Exploring all paths, backtracking problems (permutations, combinations, sudoku, N-Queens). - Detecting cycles in graphs. - Topological sorting of dependencies (build order, course prerequisites). - Finding connected components and strongly connected components (Tarjan's, Kosaraju's algorithms). - Tree traversals: preorder, inorder, postorder. - Path existence and maze solving when the shortest path is not required. - Memory-constrained searches on wide graphs. Key differences - Data structure: queue vs stack or recursion. - Order: level by level vs deep first. - Shortest path in unweighted graphs: BFS yes; DFS not guaranteed. - Memory: BFS can be high for wide graphs; DFS can be high for deep graphs. - Implementation: BFS is iterative; DFS is naturally recursive. Related algorithms - Weighted shortest paths: Dijkstra's algorithm (BFS with a priority queue), A* (adds a heuristic), Bellman-Ford for negative weights. - Iterative deepening DFS combines DFS's memory efficiency with BFS-like shortest-path guarantees. - Bidirectional BFS searches from both ends to reduce explored nodes. Interview summary: "BFS explores level by level with a queue and finds shortest paths in unweighted graphs; DFS goes deep first with a stack or recursion and suits backtracking, cycle detection and topological sorting. Both are O(V + E)."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics