解法:固定的拓扑排序模板 O(顶点数+边数)
class Solution { public: bool canFinish(int numCourses, vector>& prerequisites) { //拓扑排序判断是否是有向无环图 vector indegree(numCourses); vector > bian(numCourses); for (auto& each : prerequisites) { indegree[each[0]]++; bian[each[1]].push_back(each[0]); } queue q; for (int i = 0; i < numCourses; ++i) { if (!indegree[i]) q.push(i); } int cnt = 0; while (!q.empty()) { int frt = q.front(); q.pop(); cnt++; for (auto& each : bian[frt]) { indegree[each]--; if (!indegree[each]) q.push(each); } } if (cnt == numCourses) return true; return false; } };
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)