What is a graph?
A graph is a set of nodes, also called vertices, connected by edges. Graphs model roads, friendships, web links and many other networks. This visualizer uses an undirected graph stored as an adjacency list, where each node keeps a list of its neighbors.
Breadth-first search (BFS) visits nodes level by level using a queue, so it finds the path with the fewest edges in an unweighted graph. Depth-first search (DFS) goes as deep as it can before backing up, using recursion or a stack.
Time complexity
| Operation | Time | Notes |
|---|---|---|
| Add a node or edge | O(1) | Update the neighbor lists |
| BFS or DFS | O(V + E) | Visits each node and edge once |
| Remove a node | O(V + E) | Its edges must go too |
Try it yourself
- Press BFS and watch the queue in the Output box.
- Press DFS from the same node and compare the visiting order.
- Add an edge between two nodes, then run BFS again.
- Remove edges until the graph splits and see which nodes become unreachable.
Graph vs tree
A tree is a graph with no cycles and exactly one path between any two nodes. A general graph can have cycles and several paths, so a traversal must remember which nodes it has already visited.
Common questions
- What is the difference between BFS and DFS?
- BFS explores neighbors level by level using a queue. DFS follows one path as deep as it can before backtracking.
- What is an adjacency list?
- A way to store a graph in which every node keeps a list of the nodes it is connected to.
- When should I use BFS?
- When you want the shortest path in an unweighted graph, or need to explore everything near a starting node first.