LeetCode 207. Course Schedule

题解

这题就是拓扑排序,也可以dfs查环,思路简单,注意下如何用数据结构表示。
可参考的英文题解含DFS/BFS


Code
class Solution {
public:
    bool canFinish(int n, vectorpairint, int pres) {
        vectorunordered_setint graph(n);// build graph
        for(auto p:pres){
            graph[p.second].insert(p.first);
        }
        vectorint degrees(n,0);// indegrees list
        for(auto e:graph)
            for(int k:e) degrees[k]++;
        
        for(int i=0;in;i++){// Topological Sort
            int j;
            for(j=0;jn;j++){ // search for 0 indegree point
                if(degrees[j]==0)
                    break;
            }
            
            if(j==n) return false;// not found
            
            degrees[j]=-1;// found and set -1 to make it unvisible
            for(int k:graph[j]){// found and delete edge
                degrees[k]--;
            }
        }
        
        return true;
    }
};
最新回复(0)
/jishu8s71_2Fyx5qCF1_2FOWNZ87ifdL_2BCCvUcnTL0f7ZLQ_3D_3D4858375
8 简首页