LeetCode 802. 找到最終的安全狀態 (拓補排序、DFS)

找到最終的安全狀態

class Solution {
public:
    vector<int> c,ans;
    vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
        int n = graph.size();
        c.resize(n,0);
        for(int x=0;x<n;x++){
            if(!c[x]){
                dfs(x,graph);
            }
        }
        for(int x=0;x<n;x++){
            if(c[x]==1){
                ans.push_back(x);
            }
        }
        return ans;
    }
    bool dfs(int x,vector<vector<int>>& graph){
        c[x] = -1;
        for(int y:graph[x]){
            if(c[y]==-1){
                return 0;
            }
            if(!c[y] && !dfs(y,graph)){
                return 0;
            }
        }
        c[x] = 1;
        return 1;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章