Find Eventual Safe States
Find the nodes of a directed graph from which every path you can follow comes to an end.
A directed graph has n nodes, numbered 0 to n - 1, and graph[i]
Example 1
Output: [2,4,5,6]
Explanation: 5 and 6 are terminal. 2 and 4 lead only to 5. 0, 1 and 3 can loop 0 → 1 → 3 → 0 forever.
Example 2
Output: [4]
The Idea
Picture a town of one-way streets. Each numbered crossing is a node, and each one-way street is an arrow from one crossing to another. A driver who keeps following streets either reaches a dead end, where no street leads out, or keeps driving forever. A crossing is safe if, whatever turns the driver takes from there, the drive always stops at a dead end.
The input already lists the streets crossing by crossing. In Example 1, graph[0] = [1,2]graph[5] = []
Nodes 5 and 6, marked terminal, are the dead ends: they have no arrows out, so a path that reaches them stops. Node 2 has one arrow, to 5, and so does node 4. Every path from 2 or 4 therefore stops at 5, which puts 2, 4, 5 and 6 in the box labelled "safe: every path ends".
Now start at 0 and follow the arrows in the box labelled "cycle 0 → 1 → 3 → 0: unsafe": 0 to 1, 1 to 3, 3 back to 0, and round again without end. A path that comes back to a node it has already been on is called a cycle. Node 0 also has an arrow to 2, which ends safely, but that does not help: one path that never ends is enough to make 0 unsafe. The same goes for 1 and 3.
So when does a path never end? The graph has only n nodes, so a path longer than n steps must visit some node twice, and from there it can repeat the same loop forever. That gives the key insight: a node is unsafe exactly when some path from it reaches a cycle. Every other node is safe. The question becomes how to spot cycles, and the nodes that can reach them, without walking every path from every node.
Solution Approach
Turning that idea into code means settling three things: how to notice a cycle, what to remember about each node so it is never searched twice, and what to do with a node found unsafe. A slower way and a backward way come at the end.
Noticing a cycle
How can a search tell that it has gone round a loop? Follow the arrows from a node as deep as they go, one arrow at a time, and come back to try the next arrow only when a path has ended. This order is called depth-first search, or DFS. At any moment it has a current path, the chain of nodes from the start to where it stands.
From 0 in Example 1, the current path grows to 0, 1, 3. The arrow from 3 points to 0, which is still on that path. Reaching a node that is on the current path means the search has come round a cycle, so 3, 1 and 0 can all reach it.
Three states for each node
What does the search need to know about a node it meets? One of three things, kept in an array called state
- unvisited: the search has not looked at it yet, so it must explore it.
- visiting: the search entered it and has not finished it. Meeting it again means unsafe.
- safe: fully explored, and every arrow out of it led to a safe node. Meeting it again means safe, at once.
A node becomes safe only after all its arrows have led to safe nodes. A terminal node has no arrows to check, so it becomes safe straight away.
Leaving unsafe nodes as visiting
The search is started from each node in turn, 0 first, then 1, and so on. What happens to 0, 1 and 3 once the search from 0 finds the cycle? The search at node 3 answers "unsafe", then so do the searches at nodes 1 and 0, and all three keep the state visiting. Nothing resets it. Later, when the search is started from 1 or 3, it finds visiting and answers "unsafe" without exploring again.
Answering "unsafe" for a node left visiting is correct, because that node was found to reach a cycle earlier. It also means each node is explored at most once, so the whole graph costs one pass.
The slower way: a fresh search from every node
Why not simply search from each node separately? That means starting a new search from each node, with its own record of which nodes are on the current path, and throwing the record away afterwards. It gives the right answer, but the same parts of the graph are searched again from every start. With n nodes and E arrows, that can take about n times (n + E) steps instead of one pass.
Optional: working backward from the terminal nodes
Can the answer be built up from the dead ends instead? Count the arrows out of each node, and for each node also list the nodes that have an arrow into it. Put the terminal nodes, those with a count of 0, in a queue, a waiting line where the first node added is the first taken out. Take a node from the queue, mark it safe, and lower the count of every node with an arrow into it. A node whose count falls to 0 has all its arrows leading to safe nodes, so it joins the queue. Nodes on a cycle, or with a path to one, never reach a count of 0, so they are never marked safe.
Java Solution
The method eventualSafeNodesisSafe
- First, create the array
, with one entry per node, and an empty liststate . Java fills a newresult array with 0, which is the constantint , so every node starts unvisited.UNVISITED - A loop moves
over the nodes from 0 upward and callsi . Each safeisSafe(graph, i, state) is added toi . Becauseresult only grows, the list comes out in ascending order.i - Inside
, checkisSafe for the nodestate[u] first. If it is notu , the answer is already known:UNVISITED gives true, andSAFE gives false, for a cycle on the current path or a node that failed earlier.VISITING - Otherwise, set
tostate[u] . A loop then takes each nodeVISITING thatv has an arrow to and callsu on it. On the first false, return false at once, leavingisSafe asu .VISITING - If every
was safe, orv had no arrows at all, setu tostate[u] and return true.SAFE
The main
import java.util.ArrayList;
import java.util.List;
public class FindEventualSafeStates {
private static final int UNVISITED = 0, VISITING = 1, SAFE = 2;
public static List<Integer> eventualSafeNodes(int[][] graph) {
int n = graph.length;
int[] state = new int[n]; // every node starts UNVISITED (0)
List<Integer> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (isSafe(graph, i, state)) {
result.add(i); // i grows, so the list is in ascending order
}
}
return result;
}
private static boolean isSafe(int[][] graph, int u, int[] state) {
if (state[u] != UNVISITED) {
return state[u] == SAFE; // still VISITING: we came round a cycle
}
state[u] = VISITING;
for (int v : graph[u]) {
if (!isSafe(graph, v, state)) {
return false; // u stays VISITING, so it counts as unsafe
}
}
state[u] = SAFE; // every arrow out of u leads to an end
return true;
}
public static void main(String[] args) {
int[][] example1 = {{1, 2}, {2, 3}, {5}, {0}, {5}, {}, {}};
int[][] example2 = {{1, 2, 3, 4}, {1, 2}, {3, 4}, {0, 4}, {}};
System.out.println(eventualSafeNodes(example1));
System.out.println(eventualSafeNodes(example2));
System.out.println(eventualSafeNodes(new int[][] {{0}, {}})); // 0 points to itself
System.out.println(eventualSafeNodes(new int[][] {{1}, {2}, {}})); // chain 0 -> 1 -> 2
System.out.println(eventualSafeNodes(new int[][] {{1}, {0}})); // 0 and 1 in a loop
}
}
Running it prints:
[2, 4, 5, 6]
[4]
[1]
[0, 1, 2]
[]
The answer [2, 4, 5, 6][4][[0],[]]isSafe(0)
The chain prints [0, 1, 2]
The three states matter. A version with a plain true or false "seen" flag, which answers true for any node seen before, treats node 0 as safe when 3 points back to it. That version, run on Example 1, prints [0, 1, 2, 3, 4, 5, 6]
Complexity
Each node is explored at most once, so the cost depends on the n nodes and the E arrows of the graph.
- Time: O(n + E), because
runs its loop over a node's arrows only the first time it finds that node unvisited, and every later call returns straight from the state check.isSafe - Space: O(n), because
andstate hold at most one entry per node, and the chain of recursive calls follows one path, which never holds a node twice.result
Cycle detection with a queue, close to the backward way above, is shown in