Components and cycles
After this: Count components with one visited set, and find a cycle by ignoring the parent.
On this page · 6 sections · 4 checks
Breadth-first search and depth-first search both visit every node they can reach from the start. This raises two questions. What about the nodes a walk cannot reach? And what does it mean when a walk meets a node it has already visited?
Separate pieces
A graph does not have to be joined up. Picture six people at a party. A and B know each other. C knows D, and D knows E. F knows nobody there.
This is one graph, but it has three separate pieces. No walk can cross from one piece to another, because no edge joins them.
Each piece is called a . In a component, every node can reach every other node, and no edge leads outside it. F is a component of one node.
Counting components
A walk from one node visits exactly the nodes of its component. So we can count components by counting the walks we need to cover every node.
Go through all the nodes in turn. If a node has not been visited, start a new walk from it and add one to the count. If it has been visited, skip it. All the walks share one visited set.
- A has not been visited. Start walk 1, which visits A and B.
- B has been visited, so skip it.
- C has not been visited. Start walk 2, which visits C, D and E.
- D and E have been visited, so skip them.
- F has not been visited. Start walk 3, which visits only F.
Three walks mean three components. This code uses the dfs function from the last lesson.
def components(adj): visited = set() # shared by every walk groups = [] for node in adj: # every node gets a chance to start a walk if node not in visited: members = [] dfs(adj, node, visited, members) # marks everything reachable from node groups.append(members) return groups
parts = {"A": ["B"], "B": ["A"], "C": ["D"], "D": ["C", "E"], "E": ["D"], "F": []}print(components(parts))[['A', 'B'], ['C', 'D', 'E'], ['F']]
static List<List<String>> components(Map<String, List<String>> adj) { Set<String> visited = new HashSet<>(); // shared by every walk List<List<String>> groups = new ArrayList<>(); for (String node : adj.keySet()) { // every node gets a chance to start a walk if (!visited.contains(node)) { List<String> members = new ArrayList<>(); dfs(adj, node, visited, members); // marks everything reachable from node groups.add(members); } } return groups;}[[A, B], [C, D, E], [F]]
Here is how to read it.
visitedis created once, outside the loop, so every walk shares it.- The loop gives every node a chance to start a walk.
memberscollects the nodes of one walk, andgroupscollects one list for each component. The number of components is the length ofgroups.partsis the party graph as an adjacency list. F has an empty list because it has no edges.
Now run the three walks yourself.
- BFS from AFrom A, the walk reaches A and B, and then it has nothing left to do. The other four nodes stay at ∞.
- BFS from C
- BFS from F
Pick a start node and run an algorithm.
What a cycle is
Now for the second question. Look at the four friends again.
Start at Asha. Go to Ben, then Dev, then Cara, and then back to Asha. You came back to where you started, and you did not use any edge twice. This is called a .
Going from Asha to Ben and straight back is not a cycle, because it uses the same edge twice.
Cycles are worth finding. If file X needs file Y and file Y needs file X, neither one can be built first. In the friends graph, the cycle means that Asha has two separate routes to Dev.
Finding a cycle with a walk
A depth-first walk finds a cycle when it meets a neighbour that it has already visited. But there is a catch.
Every undirected edge is stored in both lists. So after the walk moves from Asha to Ben, it reads Ben's list and finds Asha, who is already visited. This is not a cycle. It is the same edge that the walk used to arrive.
The fix is to pass each call the node it came from, which is its parent. The walk ignores that one neighbour. Any other visited neighbour closes a real cycle.
Here is that check on the four friends, starting from Asha.
| The walk is at | Its parent | Neighbour | Result |
|---|---|---|---|
| Asha | none | Ben | Not visited. Go to Ben. |
| Ben | Asha | Asha | Visited, but it is the parent. Ignore it. |
| Ben | Asha | Dev | Not visited. Go to Dev. |
| Dev | Ben | Ben | Visited, but it is the parent. Ignore it. |
| Dev | Ben | Cara | Not visited. Go to Cara. |
| Cara | Dev | Asha | Visited, and not the parent. A cycle is found. |
def has_cycle(adj): visited = set()
def walk(node, parent): visited.add(node) for nb in adj[node]: if nb not in visited: if walk(nb, node): return True elif nb != parent: # seen before, and not the edge we came in on return True return False
for node in adj: if node not in visited and walk(node, None): return True return False
print(has_cycle(adj), has_cycle(parts))True False
static boolean hasCycle(Map<String, List<String>> adj) { Set<String> visited = new HashSet<>(); for (String node : adj.keySet()) { if (!visited.contains(node) && walk(adj, node, null, visited)) return true; } return false;}
static boolean walk(Map<String, List<String>> adj, String node, String parent, Set<String> visited) { visited.add(node); for (String nb : adj.get(node)) { if (!visited.contains(nb)) { if (walk(adj, nb, node, visited)) return true; } else if (!nb.equals(parent)) { // seen before, and not the edge we came in on return true; } } return false;}true false
Here is how to read it.
walkis depth-first search with one extra argument,parent. The first call has no parent, so it passes Nonenull.- If a neighbour has not been visited, the walk goes deeper. If that deeper call finds a cycle, the answer is passed back up.
- Otherwise the neighbour has been visited. If it is not the parent, the walk has found a cycle.
- The outer loop starts a walk from every unvisited node, so that a cycle in any component is found.
On the six-node graph, the walk goes A, B, D, C, and then C finds A. That is the cycle A–B–D–C–A, so the first answer is Truetrue. The party graph has no cycle, so the second answer is Falsefalse.
- DFS from ARun depth-first search from A, and watch for the steps that find a node already seen. From B, A has been seen, but A is B's parent, so this is not a cycle. From C, A has been seen and A is not C's parent. That closes the cycle A–B–D–C–A.
Pick a start node and run an algorithm.
Check yourself
Nodes A to F have edges A–B, C–D and D–E. How many components does the counting loop find?
Does the six-node graph (A–B, A–C, B–D, C–D, D–E, E–F) have a cycle?
In the DFS from A, the walk is at B and finds that A is already visited. Why is that not a cycle?
Complete the cycle check: a neighbour that is already visited means a cycle, unless it is the node the walk came from.
def walk(node, parent): visited.add(node) for nb in adj[node]: if nb not in visited: if walk(nb, node): return True ________________________ # ← seen before, and not the edge we came in on return True return Falsestatic boolean walk(Map<String, List<String>> adj, String node, String parent, Set<String> visited) { visited.add(node); for (String nb : adj.get(node)) { if (!visited.contains(nb)) { if (walk(adj, nb, node, visited)) return true; } ________________________ // ← seen before, and not the edge we came in on return true; } } return false;}Connect
- Count components by starting a new walk from every node the visited set has not reached.
- Find a cycle in an undirected graph: a visited neighbour that is not the parent.
- Say why the edge back to the parent must be ignored.