Connections: groups, fewest steps, cheapest route, safe order
After this: Pick BFS, DFS, Dijkstra's algorithm or a topological order from the words of a graph problem.
On this page · 6 sections · 3 checks
People who know each other, towns joined by roads, jobs that must wait for other jobs: all of these are things with connections between them. That shape is a . Each thing is a , and each connection is an , which problems often call a link. Interviewers ask four questions about graphs again and again, and each one has its own tool.
Groups: a search from each new start
The cues are "connected", "groups" and "islands". Start a search at any person, and it reaches everyone in that person's group. So count how many searches you have to start. Here the search is a , but any search works.
- Search from A: it reaches A, B and C. That is group 1.
- D was not reached, so search from D: it reaches D and E. Group 2.
- F was not reached either. Group 3, on its own.
The answer is 3. The task below runs the three searches.
- DFS from ASearch from A. Every node it reaches is in A's group. That is group 1.
- DFS from D
- DFS from F
Pick a start node and run an algorithm.
The function first builds a list of neighbours for each person, adding every link in both directions. Then it goes through the people in order. A person already in seen belongs to a group that was counted. Anyone else starts a new group, and the while loop is a DFS with a stack that marks everyone it reaches. Each person and each link is handled a fixed number of times, so the cost is O(nodes + edges).
Fewest steps: breadth-first search
On the six-node graph below, how many links is each node from A? The cue is "fewest steps" when every step costs the same. visits the nodes in layers, so the first time it reaches a node is by the fewest links: A 0, B 1, C 1, D 2, E 3, F 4. The cost is O(nodes + edges).
- BFS from ABreadth-first search from A visits the nodes one layer at a time. Read each node's distance as it is found.
Pick a start node and run an algorithm.
Cheapest route: Dijkstra's algorithm
Now each link is one-way and has a cost. What is the cheapest route from A to E? The cue is "cheapest" or "shortest" with costs on the links. BFS counts links and ignores the costs, so it takes A → B → D → E: three links, costing 4 + 1 + 3 = 8. The cheapest route is A → C → B → D → E: four links, costing 1 + 2 + 1 + 3 = 7. This is the example of Why BFS stops working.
always finishes the closest unfinished node next, using a heap. From A it finds A 0, B 3, C 1, D 4, E 7, in O((nodes + edges) log nodes) time. The task asks you to predict which node is finished last.
- Dijkstra from AStep through from A. Each pop finalises the closest node that is not finished yet.
Pick a start node and run an algorithm.
A safe order: topological order
The cues are "before this can start", "prerequisites" and "order of jobs". The answer is a : an order in which every arrow points forward. Take a job that no arrow points to, cross out its arrows, and repeat. One answer is wake, coffee, shower, dress, leave. wake, shower, coffee, dress, leave is also correct, because coffee and shower were ready at the same time. The cost is O(nodes + edges).
- Topological orderA job is ready when no arrow points at it from a job not yet done. Watch the ready list.
Pick a start node and run an algorithm.
| Cue | Tool | Time |
|---|---|---|
| "connected", "groups", "islands" | a search (DFS or BFS) from each new start | O(nodes + edges) |
| "fewest steps", every step equal | BFS | O(nodes + edges) |
| "cheapest", "shortest" with costs | Dijkstra's algorithm | O((nodes + edges) log nodes) |
| "before", "prerequisites", "order of jobs" | topological order | O(nodes + edges) |
Check yourself
Four problems. (a) The fewest stops between two stations on a train map. (b) The cheapest flight route, when every flight has a price. (c) An order to take courses so that every course comes after the ones it needs. (d) How many separate circles of friends there are. Which tools match a, b, c and d, in that order?
On the weighted graph of this lesson, why is BFS the wrong tool for the cheapest route from A to E?
The group-counting function from this lesson, with two links among six people. What does it print?
def count_groups(nodes, links): neighbours = {n: [] for n in nodes} for a, b in links: neighbours[a].append(b) neighbours[b].append(a) seen = set() groups = 0 for start in nodes: if start in seen: continue # already inside a group we counted groups += 1 # no search has reached it: a new group seen.add(start) stack = [start] while stack: # depth-first search from start node = stack.pop() for nb in neighbours[node]: if nb not in seen: seen.add(nb) stack.append(nb) return groups
print(count_groups(["A", "B", "C", "D", "E", "F"], [("A", "B"), ("C", "D")]))import java.util.*;
public class Main { static int countGroups(String[] nodes, String[][] links) { Map<String, List<String>> neighbours = new HashMap<>(); for (String n : nodes) neighbours.put(n, new ArrayList<>()); for (String[] link : links) { neighbours.get(link[0]).add(link[1]); neighbours.get(link[1]).add(link[0]); } Set<String> seen = new HashSet<>(); int groups = 0; for (String start : nodes) { if (seen.contains(start)) continue; // already inside a group we counted groups++; // no search has reached it: a new group seen.add(start); Deque<String> stack = new ArrayDeque<>(); stack.push(start); while (!stack.isEmpty()) { // depth-first search from start String node = stack.pop(); for (String nb : neighbours.get(node)) { if (!seen.contains(nb)) { seen.add(nb); stack.push(nb); } } } } return groups; }
public static void main(String[] args) { String[] nodes = {"A", "B", "C", "D", "E", "F"}; String[][] links = {{"A", "B"}, {"C", "D"}}; System.out.println(countGroups(nodes, links)); }}Honesty notes
- Count groups by starting a search from each node no search has reached yet.
- Use BFS for the fewest steps when every step costs the same, and Dijkstra's algorithm when the links have different costs.
- Say why BFS fails on costs: on the weighted graph it picks three links costing 8, while four links cost 7.
- Use a topological order for jobs that must wait for other jobs, and accept any order in which every arrow points forward.