Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/802.html
802. Find Eventual Safe States (Medium)
In a directed graph, we start at some node and every turn, walk along a directed edge of the graph. If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop.
Now, say our starting node is eventually safe if and only if we must eventually walk to a terminal node. More specifically, there exists a natural number K
so that for any choice of where to walk, we must have stopped at a terminal node in less than K
steps.
Which nodes are eventually safe? Return them as an array in sorted order.
The directed graph has N
nodes with labels 0, 1, ..., N-1
, where N
is the length of graph
. The graph is given in the following form: graph[i]
is a list of labels j
such that (i, j)
is a directed edge of the graph.
Example: Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]] Output: [2,4,5,6] Here is a diagram of the above graph.
Note:
graph
will have length at most10000
.- The number of edges in the graph will not exceed
32000
. - Each
graph[i]
will be a sorted list of different integers, chosen within the range[0, graph.length - 1]
.
Related Topics:
Depth-first Search, Graph
Solution 1. Topological Sort (DFS)
Similar to the DFS version of Topological Sort.
// OJ: https://leetcode.com/problems/find-eventual-safe-states/
// Time: O(N)
// Space: O(N)
class Solution {
vector<int> state; // -1 unvisited, 0 visiting, 1 safe, 2 unsafe
int dfs(vector<vector<int>> &G, int u) {
if (state[u] == 0) return state[u] = 2; // circle detected, unsafe
if (state[u] == 1 || state[u] == 2) return state[u];
state[u] = 0;
for (int v : G[u]) {
if (dfs(G, v) == 2) return state[u] = 2; // upstream of unsafe node is unsafe
}
return state[u] = 1;
}
public:
vector<int> eventualSafeNodes(vector<vector<int>>& G) {
state.assign(G.size(), -1);
vector<int> ans;
for (int i = 0; i < G.size(); ++i) {
dfs(G, i);
if (state[i] == 1) ans.push_back(i);
}
return ans;
}
};
Solution 2. Topological Sort (BFS) + Reverse Edges
// OJ: https://leetcode.com/problems/find-eventual-safe-states/
// Time: O(V + E)
// Space: O(V + E)
class Solution {
public:
vector<int> eventualSafeNodes(vector<vector<int>>& G) {
int N = G.size();
vector<vector<int>> R(N); // reversed graph
vector<int> indegree(N), safe(N), ans;
for (int i = 0; i < N; ++i) {
for (int j : G[i]) {
R[j].push_back(i);
indegree[i]++;
}
}
queue<int> q;
for (int i = 0; i < N; ++i) {
if (indegree[i] == 0) q.push(i);
}
while (q.size()) {
int u = q.front();
q.pop();
safe[u] = 1;
for (int v : R[u]) {
if (--indegree[v] == 0) q.push(v);
}
}
for (int i = 0; i < N; ++i) {
if (safe[i]) ans.push_back(i);
}
return ans;
}
};
-
class Solution { public List<Integer> eventualSafeNodes(int[][] graph) { int nodes = graph.length; boolean[] safe = new boolean[nodes]; List<Set<Integer>> nextNodes = new ArrayList<Set<Integer>>(); List<Set<Integer>> prevNodes = new ArrayList<Set<Integer>>(); for (int i = 0; i < nodes; i++) { nextNodes.add(new HashSet<Integer>()); prevNodes.add(new HashSet<Integer>()); } Queue<Integer> queue = new LinkedList<Integer>(); for (int i = 0; i < nodes; i++) { int[] nextArray = graph[i]; if (nextArray.length == 0) queue.offer(i); else { for (int nextNode : nextArray) { nextNodes.get(i).add(nextNode); prevNodes.get(nextNode).add(i); } } } while (!queue.isEmpty()) { int node = queue.poll(); safe[node] = true; Set<Integer> prevSet = prevNodes.get(node); for (int prevNode : prevSet) { nextNodes.get(prevNode).remove(node); if (nextNodes.get(prevNode).isEmpty()) queue.offer(prevNode); } } List<Integer> safeList = new ArrayList<Integer>(); for (int i = 0; i < nodes; i++) { if (safe[i]) safeList.add(i); } return safeList; } } ############ class Solution { private int[] color; private int[][] g; public List<Integer> eventualSafeNodes(int[][] graph) { int n = graph.length; color = new int[n]; g = graph; List<Integer> ans = new ArrayList<>(); for (int i = 0; i < n; ++i) { if (dfs(i)) { ans.add(i); } } return ans; } private boolean dfs(int i) { if (color[i] > 0) { return color[i] == 2; } color[i] = 1; for (int j : g[i]) { if (!dfs(j)) { return false; } } color[i] = 2; return true; } }
-
// OJ: https://leetcode.com/problems/find-eventual-safe-states/ // Time: O(V + E) // Space: O(V) class Solution { vector<int> state; // -1 unvisited, 0 visiting, 1 safe, 2 unsafe int dfs(vector<vector<int>> &G, int u) { if (state[u] == 0) return state[u] = 2; // circle detected, unsafe if (state[u] == 1 || state[u] == 2) return state[u]; state[u] = 0; for (int v : G[u]) { if (dfs(G, v) == 2) return state[u] = 2; // upstream of unsafe node is unsafe } return state[u] = 1; } public: vector<int> eventualSafeNodes(vector<vector<int>>& G) { state.assign(G.size(), -1); vector<int> ans; for (int i = 0; i < G.size(); ++i) { if (dfs(G, i) == 1) ans.push_back(i); } return ans; } };
-
class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: def dfs(i): if color[i]: return color[i] == 2 color[i] = 1 for j in graph[i]: if not dfs(j): return False color[i] = 2 return True n = len(graph) color = [0] * n return [i for i in range(n) if dfs(i)] ############ class Solution(object): def eventualSafeNodes(self, graph): """ :type graph: List[List[int]] :rtype: List[int] """ #color[i], 0 means not visited. 1 means safe. 2 means unsafe. color = [0] * len(graph) res = [] for start in range(len(graph)): if self.dfs(graph, start, color): res.append(start) res.sort() return res def dfs(self, graph, start, color): # 返回start节点是否是安全,如果是,返回True if color[start] != 0: return color[start] == 1 color[start] = 2 for e in graph[start]: if not self.dfs(graph, e, color): return False color[start] = 1 return True
-
func eventualSafeNodes(graph [][]int) []int { n := len(graph) color := make([]int, n) var dfs func(int) bool dfs = func(i int) bool { if color[i] > 0 { return color[i] == 2 } color[i] = 1 for _, j := range graph[i] { if !dfs(j) { return false } } color[i] = 2 return true } ans := []int{} for i := range graph { if dfs(i) { ans = append(ans, i) } } return ans }
-
/** * @param {number[][]} graph * @return {number[]} */ var eventualSafeNodes = function (graph) { const n = graph.length; const color = new Array(n).fill(0); function dfs(i) { if (color[i]) { return color[i] == 2; } color[i] = 1; for (const j of graph[i]) { if (!dfs(j)) { return false; } } color[i] = 2; return true; } let ans = []; for (let i = 0; i < n; ++i) { if (dfs(i)) { ans.push(i); } } return ans; };