Leetcode 802. Find Eventual Safe States
Leetcode 802: Find Eventual Safe States
Given a directed graph with n
nodes labeled from 0
to n-1
, where each node has a list of directed edges to other nodes. Implement a function eventualSafeNodes
that returns an array of all the nodes that are eventually safe. A node is eventually safe if, and only if, every possible path starting from that node leads to a terminal node (i.e., a node with no outgoing edges).
List<Integer> eventualSafeNodes(int[][] graph)
0
: Node not yet visited.1
: Node is in current path (potential cycle).2
: Node is fully processed and confirmed as safe.n
is the number of nodes and e
is the number of edges, since every node and edge is processed once.import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Solution {
public List<Integer> eventualSafeNodes(int[][] graph) {
int n = graph.length;
int[] state = new int[n];
List<Integer> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (dfs(graph, state, i)) {
result.add(i);
}
}
Collections.sort(result);
return result;
}
private boolean dfs(int[][] graph, int[] state, int node) {
if (state[node] != 0) {
return state[node] == 2; // Return true if node is safe (state 2)
}
state[node] = 1; // Mark node as visiting (part of the current path)
for (int next : graph[node]) {
if (state[next] == 2) continue; // If next node is safe, skip it
if (state[next] == 1 || !dfs(graph, state, next)) {
return false; // Found a cycle or a node that leads to a cycle
}
}
state[node] = 2; // Mark node as safe
return true;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[][] graph = // use example above
System.out.println(sol.eventualSafeNodes(graph)); // Output: [2, 4, 5, 6]
}
}
This solution efficiently checks and returns the eventual safe nodes in the graph.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?