802. Find Eventual Safe States
Problem
graph[i] lists the directed edges out of node i. A terminal node has no outgoing edges; a node is safe if every path starting from it ends at a terminal node. Return all safe nodes in ascending order.
Example: [[1,2],[2,3],[5],[0],[5],[],[]] → [2,4,5,6]
Constraints: n ≤ 10⁴.
A node is safe iff no path from it reaches a cycle. Three-color DFS: 0 = unvisited, 1 = on stack, 2 = safe. Reaching a node with color 1 means a cycle → unsafe. (Alternatively: Kahn's on the reversed graph.)
Complexity: O(V + E).
class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
color = [0] * len(graph)
def safe(u):
if color[u]:
return color[u] == 2
color[u] = 1
if all(safe(v) for v in graph[u]):
color[u] = 2
return True
return False # stays 1 -> unsafe
return [u for u in range(len(graph)) if safe(u)]
assert Solution().eventualSafeNodes([[1, 2], [2, 3], [5], [0], [5], [], []]) == [2, 4, 5, 6]
assert Solution().eventualSafeNodes([[1, 2, 3, 4], [1, 2], [3, 4], [0, 4], []]) == [4]
class Solution {
public List<Integer> eventualSafeNodes(int[][] graph) {
int[] color = new int[graph.length];
List<Integer> res = new ArrayList<>();
for (int u = 0; u < graph.length; u++) if (safe(graph, u, color)) res.add(u);
return res;
}
private boolean safe(int[][] g, int u, int[] color) {
if (color[u] != 0) return color[u] == 2;
color[u] = 1;
for (int v : g[u]) if (!safe(g, v, color)) return false;
color[u] = 2;
return true;
}
}
func eventualSafeNodes(graph [][]int) []int {
color := make([]int, len(graph)) // 0 unvisited, 1 on the path or unsafe, 2 safe
var safe func(u int) bool
safe = func(u int) bool {
if color[u] != 0 {
return color[u] == 2
}
color[u] = 1
for _, v := range graph[u] {
if !safe(v) {
return false // stays 1: unsafe
}
}
color[u] = 2
return true
}
res := []int{}
for u := range graph {
if safe(u) {
res = append(res, u)
}
}
return res
}