[LeetCode] Find Eventual Safe States

802. Find Eventual Safe States

There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].

A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node.

Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int dp[10000];
int helper(vector<vector<int>>& g, int n) {
if(dp[n] != -1) return dp[n];
if(g[n].empty()) return dp[n] = 1;
dp[n] = 0;
int mask = 1;
for(auto near : g[n])
mask &= helper(g,near);
return dp[n] = mask;
}
public:
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
memset(dp,-1,sizeof(dp));
int n = graph.size();
vector<int> res;
for(int i = 0; i < n; i++)
if(helper(graph,i))
res.push_back(i);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/29/PS/LeetCode/find-eventual-safe-states/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.