题目:
There are a total of n courses you have to take, labeled from 0
to n
- 1
.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
由题目,我们可以用图来解决这道题,第一个输入为顶点数,第二个输入为边。这样对图进行拓扑排序,若拓扑排序的结果可以将整个图遍历,则返回true,否则返回false。
代码如下:
#include <iostream>
#include <vector>
#include <list>
#include <queue>
using namespace std;
struct Node
{
int name;
int du;
Node(int name_, int du_) {
name = name_;
du = du_;
}
Node() {
name = 0;
du = 0;
}
};
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<list<Node> > graph;
for (int i = 0; i < numCourses; i++) {
// cout << "in1 " << endl;
list<Node> temp;
Node a(i,0);
temp.push_back(a);
graph.push_back(temp);
}
for (int i = 0; i < prerequisites.size(); i++) {
// cout << "in2 " << endl;
Node a(prerequisites[i].first, 0);
graph[prerequisites[i].second].push_back(a);
graph[prerequisites[i].first].front().du++;
}
queue<Node> que;
for (int i = 0; i < graph.size(); i++) {
if (graph[i].front().du == 0) {
que.push(graph[i].front());
}
}
int count = 0;
while (!que.empty()) {
// cout << "in";
Node t = que.front();
que.pop();
count++;
list<Node> ::iterator it = graph[t.name].begin();
for (it; it != graph[t.name].end(); it++) {
graph[it->name].front().du--;
if (graph[it->name].front().du == 0) {
que.push(graph[it->name].front());
}
}
}
if (que.empty()) {
if (count == graph.size()) {
return 1;
}
else {
return 0;
}
}
}
};
测试结果: