//in[i]记录修第i门课需要修其他课的数量,当为in[i]0时,这门课可以修
//next[i][j]=1记录第j门课的基础课之一是i
//用队列把当前可修的课in[i]=0压入,弹出后把next[i][j]=1对应的in[j]--
//用一个int记录压入队列的in[i]=0的个数,最后如果等于课程数则true否则返回false
#include<vector>
#include<iostream>
#include<queue>
using namespace std;
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
if (numCourses == 0)
return true;
int finish = 0;
vector<int> in(numCourses, 0);
vector<vector<int>> next(numCourses, vector<int>(numCourses));
for (int i = 0; i < prerequisites.size(); ++i) {
next[prerequisites[i][1]][prerequisites[i][0]] = 1; //next[i][j]=1 表示存在要修第j门课,必须修第i门课
in[prerequisites[i][0]]++; //in[i]表示修第i门课总共需要修in[i]
}
queue<int> fin;
for (int i = 0; i < numCourses; ++i) {
if (in[i] == 0) {
fin.push(i);
finish++;
}
}
while (!fin.empty()) {
int tmp = fin.front();
fin.pop();
for (int i = 0; i < numCourses; ++i) {
if (next[tmp][i] == 1) {
in[i]--;
if (in[i] == 0)
{
fin.push(i);
finish++;
}
}
}
}
return finish == numCourses ? true : false;
}
//测试
int main() {
vector<vector<int>> a;
vector<int> b;
b.push_back(1);
b.push_back(0);
a.push_back(b);
vector<int> c;
c.push_back(0);
c.push_back(1);
a.push_back(c);
/*vector<int> d;
d.push_back(1);
d.push_back(2);
a.push_back(d);*/
if (canFinish(2, a))
cout << "true!" << endl;
else
cout << "false!" << endl;
return 0;
}
leetcode课程表
最新推荐文章于 2024-08-26 16:05:51 发布