LC802-找到最终的安全状态
802. 找到最终的安全状态
出度为0的点是安全的,可以到达安全点的点也是安全的,因此反向建图拓扑排序即可。
const int N = 1e4 + 10;
const int M = 4e4 + 10;
int d[N],q[N],hh,tt = -1;
int h[N],e[M],ne[M],idx;
class Solution {
public:
void add(int a, int b){e[idx] = b,ne[idx] = h[a], h[a] = idx++;}
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
memset(h,-1,sizeof h),idx = 0,hh = 0, tt = -1;
memset(d,0,sizeof d);
int n = graph.size();
for(int i = 0; i < n; ++i)
for(int j = 0; j < graph[i].size(); ++j){
d[i]++;
add(graph[i][j],i);
}
for(int i = 0; i < n; ++i)if(!d[i])q[++tt] = i;
while(hh <= tt){
auto t = q[hh++];
for(int i = h[t]; ~i; i = ne[i]){
int j = e[i];
if(!(--d[j]))q[++tt] = j;
}
}
vector<int>ans;
for(int i = 0; i < n; ++i)if(!d[i])ans.push_back(i);
return ans;
}
};