Graphs: BFS and DFS
A graph is a set of nodes connected by edges - cities and roads, users and friendships, web pages and links. Store it as an adjacency list: each node maps to its neighbours.
Graphs model networks - cities, friends, dependencies. BFS, DFS and Dijkstra are the core algorithms, and recognising that a problem is a graph is often the hardest step.
Example
DFS: count connected groups
Example
Dijkstra: cheapest path with weights
Example
BFS uses a queue and finds the fewest edges. DFS uses recursion (or a stack) and explores deep first. Dijkstra uses a priority queue for weighted edges (costs must not be negative).
Key points
- Store graphs as adjacency lists.
- BFS for fewest edges; DFS to explore.
- Dijkstra uses a PriorityQueue for weighted paths.
📝 Test yourself
1. Which finds the path with the fewest edges in an unweighted graph?
2. Which data structure does Dijkstra's algorithm use?
3. Fill in the Map method that creates a list for a new key:
g.(a, k -> new ArrayList<>()).add(b);
