Graph Traversal (BFS & DFS)
Interactive graph sandbox visualizing Queue-based BFS and Call Stack DFS.
Click a node to start from it. Green edges form the traversal tree.
About this tool
Breadth-first search (BFS) and depth-first search (DFS) are the two basic ways to explore a graph. BFS uses a queue and visits nodes in rings of increasing distance from the start; DFS uses a stack (or recursion) and follows one path as deep as it can before backtracking. Almost every graph algorithm — shortest paths, connected components, cycle detection, topological sort — is built on one of them.
This lab runs both on the same graph, which contains cycles on purpose. It shows the queue or call stack at every step, marks visited nodes, draws the traversal tree in green and explains why already-visited neighbours are skipped.
How to use Graph Traversal (BFS & DFS)
- Choose BFS or DFS and click a node to use it as the start.
- Press play or step through. The side panel shows the queue (front to back) or the call stack (top to bottom).
- Watch the visit order grow. Green edges are the edges that discovered each node for the first time.
- Switch algorithms from the same start and compare the order and the shape of the tree.
Examples
BFS from A
A–B, A–C, B–D, C–D, D–E
A, B, C, D, E — D is reached once, from B; the edge C–D is skipped because D is already visited
DFS from A
Same graph, neighbours in alphabetical order
A, B, D, C, E — DFS dives A→B→D→C, backtracks to D, then visits E
Implementation in five languages
The same algorithm in Python, JavaScript, Java, Go and C++. Each program is complete and runnable; the comments show what it prints.
from collections import deque
graph = {
"A": ["B", "C"],
"B": ["D", "E"],
"C": ["F"],
"D": [],
"E": ["F"],
"F": [],
}
def bfs(start):
order, seen, queue = [], {start}, deque([start])
while queue:
node = queue.popleft()
order.append(node)
for nxt in graph[node]:
if nxt not in seen: # mark when enqueued, not when visited
seen.add(nxt)
queue.append(nxt)
return order
def dfs(start):
order, seen = [], set()
def visit(node):
seen.add(node)
order.append(node)
for nxt in graph[node]:
if nxt not in seen:
visit(nxt)
visit(start)
return order
print(bfs("A")) # ['A', 'B', 'C', 'D', 'E', 'F']
print(dfs("A")) # ['A', 'B', 'D', 'E', 'F', 'C'] const graph = {
A: ['B', 'C'],
B: ['D', 'E'],
C: ['F'],
D: [],
E: ['F'],
F: [],
};
function bfs(start) {
const order = [];
const seen = new Set([start]);
const queue = [start];
for (let head = 0; head < queue.length; head++) {
const node = queue[head];
order.push(node);
for (const next of graph[node]) {
if (!seen.has(next)) { // mark when enqueued, not when visited
seen.add(next);
queue.push(next);
}
}
}
return order;
}
function dfs(start) {
const order = [];
const seen = new Set();
const visit = (node) => {
seen.add(node);
order.push(node);
for (const next of graph[node]) {
if (!seen.has(next)) visit(next);
}
};
visit(start);
return order;
}
console.log(bfs('A').join(' ')); // A B C D E F
console.log(dfs('A').join(' ')); // A B D E F C import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
public class Main {
static final Map<String, List<String>> GRAPH = Map.of(
"A", List.of("B", "C"),
"B", List.of("D", "E"),
"C", List.of("F"),
"D", List.of(),
"E", List.of("F"),
"F", List.of()
);
static List<String> bfs(String start) {
List<String> order = new ArrayList<>();
Set<String> seen = new HashSet<>(List.of(start));
Queue<String> queue = new ArrayDeque<>(List.of(start));
while (!queue.isEmpty()) {
String node = queue.poll();
order.add(node);
for (String next : GRAPH.get(node)) {
if (seen.add(next)) queue.add(next); // mark when enqueued
}
}
return order;
}
static void dfs(String node, Set<String> seen, List<String> order) {
seen.add(node);
order.add(node);
for (String next : GRAPH.get(node)) {
if (!seen.contains(next)) dfs(next, seen, order);
}
}
public static void main(String[] args) {
System.out.println(bfs("A")); // [A, B, C, D, E, F]
List<String> order = new ArrayList<>();
dfs("A", new HashSet<>(), order);
System.out.println(order); // [A, B, D, E, F, C]
}
} package main
import "fmt"
var graph = map[string][]string{
"A": {"B", "C"},
"B": {"D", "E"},
"C": {"F"},
"D": {},
"E": {"F"},
"F": {},
}
func bfs(start string) []string {
var order []string
seen := map[string]bool{start: true}
queue := []string{start}
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
order = append(order, node)
for _, next := range graph[node] {
if !seen[next] { // mark when enqueued, not when visited
seen[next] = true
queue = append(queue, next)
}
}
}
return order
}
func dfs(start string) []string {
var order []string
seen := map[string]bool{}
var visit func(string)
visit = func(node string) {
seen[node] = true
order = append(order, node)
for _, next := range graph[node] {
if !seen[next] {
visit(next)
}
}
}
visit(start)
return order
}
func main() {
fmt.Println(bfs("A")) // [A B C D E F]
fmt.Println(dfs("A")) // [A B D E F C]
} #include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
using Graph = std::map<std::string, std::vector<std::string>>;
const Graph graph = {
{"A", {"B", "C"}},
{"B", {"D", "E"}},
{"C", {"F"}},
{"D", {}},
{"E", {"F"}},
{"F", {}},
};
std::vector<std::string> bfs(const std::string& start) {
std::vector<std::string> order;
std::set<std::string> seen = {start};
std::queue<std::string> queue;
queue.push(start);
while (!queue.empty()) {
std::string node = queue.front();
queue.pop();
order.push_back(node);
for (const auto& next : graph.at(node)) {
if (seen.insert(next).second) queue.push(next); // mark when enqueued
}
}
return order;
}
void dfs(const std::string& node, std::set<std::string>& seen, std::vector<std::string>& order) {
seen.insert(node);
order.push_back(node);
for (const auto& next : graph.at(node)) {
if (!seen.count(next)) dfs(next, seen, order);
}
}
void print(const std::vector<std::string>& v) {
for (const auto& s : v) std::cout << s << ' ';
std::cout << '\n';
}
int main() {
print(bfs("A")); // A B C D E F
std::set<std::string> seen;
std::vector<std::string> order;
dfs("A", seen, order);
print(order); // A B D E F C
} Practice on LeetCode
Classic problems that use this algorithm. Try them after working through the lab. Links open on LeetCode.
When to use which
- BFS finds the shortest path in an unweighted graph (fewest edges) and is natural for “within k hops” queries.
- DFS is the basis of cycle detection, topological sorting, strongly connected components and maze solving; it uses memory proportional to the path depth, not the frontier width.
- Both run in O(V + E) time with an adjacency list.
The visited set
On a graph with cycles, a traversal that does not remember where it has been loops forever. BFS should mark a node visited when it is enqueued, not when it is dequeued; otherwise the same node can enter the queue several times.
Frequently asked questions
Everything you need to know about this tool and data security.
Does the order of neighbours matter?
It changes the visit order and the traversal tree, but not the set of reachable nodes or, for BFS, the distances.
Recursive or iterative DFS?
They are equivalent; the recursive version uses the call stack. On very deep graphs an explicit stack avoids stack-overflow errors.
What about weighted graphs?
BFS no longer gives shortest paths when edges have different weights. Use Dijkstra’s algorithm (see the Dijkstra lab) for non-negative weights.
Is my data safe when using this tool?
Yes, 100% safe. This tool operates entirely inside your web browser using client-side JavaScript and WebAssembly. Your data never touches any external server.
Related Tools
Step-by-step shortest path exploration with relaxation table and priority queue.
Disjoint set union simulator comparing rank union and path compression.
Interactive BST visualizer with insertion, deletion, and tree traversals.
Featured Projects tech-fun.net
Explore more AI & productivity tools
Nihongo GameBox
Master Japanese typing, Kana, and JLPT N5–N1 vocabulary through interactive retro arcade games.
ResumeGPT
Tailors CVs and cover letters to every job opportunity with a multi-agent LLM pipeline, job tracking, and scheduled discovery.
CollectMind
Turns your bookmarks into a searchable AI knowledge base — entirely on-device, powered by Chrome's built-in Gemini Nano.