1. 程式人生 > 其它 >LC802-找到最終的安全狀態

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;
    }
};