LeetCode -- 207. 课程表 (拓扑排序)
经典拓扑排序的应用,用拓扑排序的算法看看原图中是否有一个合法的拓扑序。
class Solution { public: const static int N = 2010, M = 5010; int h[N], e[M], ne[M], idx; int d[N], q[N]; void add(int a, int b) { e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ; } bool canFinish(int numCourses, vector<vector<int>>& prerequisites) { memset(h, -1, sizeof h); for(auto &it : prerequisites) { add(it[1], it[0]); d[it[0]] ++ ; } auto f = [&]() { int hh = 0, tt = -1; for(int i = 0; i < numCourses; i ++ ) { if(!d[i]) q[ ++ tt] = i; } while(hh <= tt) { int t = q[hh ++ ]; for(int i = h[t]; ~i; i = ne[i]) { int j = e[i]; if( -- d[j] == 0) q[ ++ tt] = j; } } return tt == numCourses - 1; }; return f(); } };
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: din = [0] * numCourses queue = deque() edges = [[] for _ in range(numCourses)] for cur, pre in prerequisites: din[cur] += 1 edges[pre].append(cur) cnt = 0 for i in range(len(din)): if not din[i]: queue.append(i) cnt += 1 while queue: t = queue.popleft() for cur in edges[t]: din[cur] -= 1 if not din[cur]: queue.append(cur) cnt += 1 return cnt == numCourses