Breadth First Search (BFS) and Depth First Search (DFS): short note
BFS and DFS are the two basic uninformed (blind) search strategies in Artificial Intelligence. "Uninformed" means they use no knowledge about how close a state is to the goal; they only know how to generate the next states. Both are also the standard ways to traverse a tree or graph in data structures.
i. Breadth First Search (BFS)
BFS starts at the root (initial state) and visits every node at the current depth before it moves to the next depth level. It keeps the frontier in a queue (first in, first out), so the shallowest unexpanded node is always expanded first.
Algorithm for BFS (the NODE-LIST form used in many AI textbooks, for example Rich and Knight's Artificial Intelligence):
- Create a variable called NODE-LIST and set it to the initial state.
- Until a goal state is found or NODE-LIST is empty, do:
- Remove the first element from NODE-LIST and call it E. If NODE-LIST was empty, quit.
- For each way that each rule can match the state described in E: apply the rule to generate a new state.
- If the new state is a goal state, quit and return this state.
- Otherwise, add the new state to the end of NODE-LIST.
ii. Depth First Search (DFS)
DFS starts at the root and follows one branch as deep as it can. When it reaches a node with no unvisited successor (a dead end), it backtracks to the most recent node that still has an unexplored successor. The frontier is a stack (last in, first out), either an explicit one or the call stack of a recursive function.
Algorithm for DFS:
- If the initial state is a goal state, quit and return success.
- Otherwise, do the following until success or failure is signalled:
- Generate a successor E of the initial state. If there are no more successors, signal failure.
- Call Depth-First Search with E as the initial state.
- If success is returned, signal success. Otherwise continue in this loop.
In one line: BFS explores level by level with a queue and finds the shallowest goal; DFS explores branch by branch with a stack and uses far less memory.
Worked example: tracing BFS and DFS on one graph
Take this small undirected graph. The neighbours of each node are listed in the order the algorithm will try them:
A: B, C
B: A, D, E
C: A, F
D: B
E: B, F
F: C, E
BFS trace from A
A node is marked visited when it is added to the queue, so no node is queued twice.
| Step | Node removed | Neighbours added | Queue after step |
|---|---|---|---|
| 0 | - | A | [A] |
| 1 | A | B, C | [B, C] |
| 2 | B | D, E (A already seen) | [C, D, E] |
| 3 | C | F | [D, E, F] |
| 4 | D | none | [E, F] |
| 5 | E | none (F already queued) | [F] |
| 6 | F | none | [ ] |
BFS order: A, B, C, D, E, F. Notice that the nodes come out in order of distance from A: A (0 edges), then B and C (1 edge), then D, E, F (2 edges).
DFS trace from A
DFS goes A → B → D. D has no unvisited neighbour, so it backtracks to B and tries E. From E it goes to F, and from F to C. All of A's other neighbours are now visited, so the search ends.
| Step | Current node | Action | Path (stack) after step |
|---|---|---|---|
| 1 | A | visit A, go to first unvisited neighbour B | A |
| 2 | B | visit B, go to D | A, B |
| 3 | D | visit D; dead end, backtrack | A, B, D |
| 4 | B | next unvisited neighbour is E | A, B |
| 5 | E | visit E, go to F | A, B, E |
| 6 | F | visit F, go to C | A, B, E, F |
| 7 | C | visit C; all neighbours seen, backtrack to A and stop | A, B, E, F, C |
DFS order: A, B, D, E, F, C. A common mistake is to write A, B, D, E, C, F for this graph. That would be correct for a tree where F hangs only under C, but here E is also connected to F, so DFS reaches F through E before it ever returns to C.
The traversal order depends on the order of neighbours in the adjacency list. If an exam question does not fix an order, state the order you assumed (alphabetical is the usual choice).
BFS and DFS in Python
The program below implements BFS, recursive DFS, iterative (stack-based) DFS, and a BFS that returns the shortest path. It uses collections.deque because removing from the left of a Python list is O(n), while deque.popleft() is O(1).
from collections import deque
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E'],
}
def bfs(graph, start):
visited = {start} # mark when a node is put in the queue
queue = deque([start])
order = []
while queue:
node = queue.popleft() # FIFO: oldest node first
order.append(node)
for nb in graph[node]:
if nb not in visited:
visited.add(nb)
queue.append(nb)
return order
def dfs(graph, node, visited=None):
if visited is None:
visited = []
visited.append(node)
for nb in graph[node]:
if nb not in visited:
dfs(graph, nb, visited) # go deeper before trying the next neighbour
return visited
def dfs_iterative(graph, start):
visited, stack = [], [start]
while stack:
node = stack.pop() # LIFO: newest node first
if node in visited:
continue
visited.append(node)
for nb in reversed(graph[node]): # reversed keeps the same order as the recursive version
if nb not in visited:
stack.append(nb)
return visited
def shortest_path(graph, start, goal):
parent = {start: None}
queue = deque([start])
while queue:
node = queue.popleft()
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1]
for nb in graph[node]:
if nb not in parent:
parent[nb] = node
queue.append(nb)
return None
print("BFS:", bfs(graph, 'A'))
print("DFS (recursive):", dfs(graph, 'A'))
print("DFS (stack):", dfs_iterative(graph, 'A'))
print("Shortest path A -> F:", shortest_path(graph, 'A', 'F'))
Output:
BFS: ['A', 'B', 'C', 'D', 'E', 'F']
DFS (recursive): ['A', 'B', 'D', 'E', 'F', 'C']
DFS (stack): ['A', 'B', 'D', 'E', 'F', 'C']
Shortest path A -> F: ['A', 'C', 'F']
Two details matter here. First, BFS marks a node visited when it is enqueued; if you mark it only when it is dequeued, the same node can sit in the queue several times (in this graph, F would be queued twice). Second, the iterative DFS pushes neighbours in reverse so that the first neighbour is popped first, which makes its output match the recursive version.
BFS and DFS in C (adjacency matrix)
The same graph in C, with vertices numbered 0 to 5 (A to F). An adjacency matrix keeps the code short; for large sparse graphs an adjacency list is the better choice.
#include <stdio.h>
#define N 6 /* vertices: 0=A, 1=B, 2=C, 3=D, 4=E, 5=F */
int adj[N][N] = {
{0,1,1,0,0,0}, /* A: B, C */
{1,0,0,1,1,0}, /* B: A, D, E */
{1,0,0,0,0,1}, /* C: A, F */
{0,1,0,0,0,0}, /* D: B */
{0,1,0,0,0,1}, /* E: B, F */
{0,0,1,0,1,0} /* F: C, E */
};
void bfs(int start) {
int queue[N], front = 0, rear = 0;
int visited[N] = {0};
queue[rear++] = start;
visited[start] = 1;
while (front < rear) {
int v = queue[front++];
printf("%d ", v);
for (int u = 0; u < N; u++) {
if (adj[v][u] && !visited[u]) {
visited[u] = 1;
queue[rear++] = u; /* each vertex enters the queue once, so N slots are enough */
}
}
}
printf("\n");
}
int seen[N];
void dfs(int v) {
seen[v] = 1;
printf("%d ", v);
for (int u = 0; u < N; u++)
if (adj[v][u] && !seen[u])
dfs(u);
}
int main(void) {
printf("BFS from 0: ");
bfs(0);
printf("DFS from 0: ");
dfs(0);
printf("\n");
return 0;
}
Output:
BFS from 0: 0 1 2 3 4 5
DFS from 0: 0 1 3 4 5 2
Read the numbers back as letters and you get the same orders as the trace: BFS A B C D E F, DFS A B D E F C. For a longer C walkthrough with a queue implemented separately, see this BFS tutorial in C.
Comparison: BFS vs DFS
In data structures, complexity is written in terms of vertices V and edges E. In AI search, where the graph is usually generated on the fly and may be huge, it is written in terms of the branching factor b, the depth of the shallowest goal d and the maximum depth m (notation from Russell and Norvig, Artificial Intelligence: A Modern Approach).
| Feature | BFS | DFS |
|---|---|---|
| Frontier data structure | Queue (FIFO) | Stack (LIFO) or recursion |
| Order of exploration | Level by level | One branch to the end, then backtrack |
| Time on an explicit graph | O(V + E) with adjacency list, O(V²) with matrix | O(V + E) with adjacency list, O(V²) with matrix |
| Time in AI search | O(bd) | O(bm) |
| Memory in AI search | O(bd): stores a whole level | O(b·m): stores one path plus siblings |
| Complete? | Yes, if b is finite | No in infinite-depth spaces or with cycles (unless visited states are tracked) |
| Optimal? | Yes, when every step has the same cost | No, the first solution found may be deep |
| Typical uses | Shortest path in unweighted graphs, level order traversal, nearest match | Cycle detection, topological sort, backtracking puzzles, path existence |
Neither algorithm is better in general. BFS is the right tool when you need the shortest (fewest-edge) answer and the space is small enough to hold a level in memory. DFS is the right tool when memory is tight, solutions are deep, or you need to explore every possibility (as in backtracking). The practical advantages and limitations are covered in more detail in advantages and disadvantages of BFS and DFS.
Where BFS and DFS are used
BFS
- Shortest path in an unweighted graph: the first time BFS reaches a node, it has used the fewest edges (the
shortest_pathfunction above). - Social networks: finding people within one, two or three connections of a user.
- Web crawlers and network broadcast: visiting pages or routers in rings around a starting point.
- Connected components and bipartite checking: run BFS from every unvisited node; colour levels alternately to test if a graph is two-colourable.
- Garbage collection: Cheney's copying collector scans live objects in BFS order.
DFS
- Cycle detection in directed and undirected graphs.
- Topological sorting of tasks with dependencies (a directed acyclic graph).
- Backtracking: Sudoku, N-Queens, maze solving and other constraint problems.
- Strongly connected components (Tarjan's and Kosaraju's algorithms) and finding articulation points.
In AI problem solving, the state-space puzzles in this series, such as the water jug problem, are usually solved first with BFS or DFS before moving on to informed methods.
Common mistakes and edge cases
- No visited set on a graph. On a tree it is not needed, but on a graph with cycles both algorithms can loop forever.
- Using BFS on a weighted graph. BFS minimises the number of edges, not the total cost. Use uniform-cost search or Dijkstra's algorithm when edges have different costs.
- Deep recursion. Recursive DFS on a long path can hit Python's default recursion limit (about 1000 frames). Use the stack-based version for big graphs.
- Disconnected graphs. One call only reaches the start node's component. Loop over all nodes and start a new search from each unvisited one.
- Start node is the goal. Check the start state before expanding anything.
Beyond BFS and DFS
Iterative deepening DFS runs DFS with depth limits 0, 1, 2, ... It keeps DFS's small memory, O(b·d), and is complete and optimal for equal step costs, like BFS. When you do have an estimate of the distance to the goal, informed searches do better: best-first search always expands the node that looks closest, and the A* algorithm adds the cost already paid, which makes it optimal with an admissible heuristic. See heuristic search techniques for how such estimates are designed.
Search algorithms like these are part of the problem-solving unit in Uncodemy's Artificial Intelligence course.


