【leedcode】207. Course Schedule

本文介绍了一种通过图的拓扑排序算法判断是否能完成所有课程的方法。针对给定的课程总数及先修课程关系,利用邻接表表示图,并通过队列实现拓扑排序过程,最终确定所有课程是否能被成功完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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;
}
}
}


};


测试结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值