# Dfs Vs Bfs

> Choose between DFS and BFS for graph traversal problems. Use when deciding whether to explore depth-first (cycle detection, paths) or breadth-first (shortest path, levels).

- Skill: `knoopx/dfs-vs-bfs` (Agent Skill)
- Install (CLI): `npx skillmds@latest add knoopx/dfs-vs-bfs`
- Raw SKILL.md: https://api.skillmd.com/api/skills/knoopx/dfs-vs-bfs/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: knoopx (https://skillmd.com/u/knoopx)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/knoopx/dfs-vs-bfs

---


## When to use

DFS (stack/recursion) explores one branch fully before backtracking. BFS (queue) explores level-by-level.

## Rules

- If the problem asks "shortest" or "minimum steps" on an unweighted graph, ALWAYS choose BFS
- If it asks "all paths," "can we reach," or "count islands," DFS is simpler
- NEVER use BFS for cycle detection — DFS is the right tool
- Both visit each node once: O(V+E) time

## DFS use cases

Cycle detection, topological sort, path existence, connected components, backtracking puzzles, flood fill.

## BFS use cases

Shortest unweighted path, level-order traversal, nearest neighbor, minimum steps.

## Example

"Count islands" → DFS flood-fill on 2D grid. "Shortest path in maze" → BFS with queue tracking (row, col, distance).

