207. Course Schedule
题意:每个课程会有一个先修课程,给定一张图,判断能否按顺序修完所有课程
我的思路:拓扑排序裸题
我的代码:
class Solution { public: struct Node { int to, next; }; bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { if (prerequisites.size() == 0) return 1; Node edge[prerequisites.size()]; int head[numCourses], que[numCourses], iq = 0, indegree[numCourses]; memset(head, -1, sizeof(head)); memset(indegree, 0, sizeof(indegree)); for (int i = 0; i < prerequisites.size(); i++) { edge[i].to = prerequisites[i].first; indegree[prerequisites[i].first]++; edge[i].next = head[prerequisites[i].second]; head[prerequisites[i].second] = i; } for (int i = 0; i < numCourses; i++) if (indegree[i] == 0) que[iq++] = i; for (int i = 0; i < iq; i++) { for (int k = head[que[i]]; k != -1; k = edge[k].next) { indegree[edge[k].to]--; if (indegree[edge[k].to] == 0) que[iq++] = edge[k].to; } } for (int i = 0; i < numCourses; i++) if (indegree[i] != 0) return 0; return 1; } };
时间: 2024-10-11 17:33:12