【leedcode】210. Course Schedule II

本文介绍了一种基于拓扑排序的课程排序算法实现方法,用于解决给定先修课程约束下的课程学习顺序问题。通过构建图结构并利用队列进行广度优先搜索,实现了有效的课程排序。

摘要生成于 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, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

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 the correct course order is [0,1]

4, [[1,0],[2,0],[3,1],[3,2]]

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].




分析:较之于之前的直接判断,本题增加了输出可能结果的要求。所以需要在拓扑排序的时候直接将排序的路径保存下来。代码如下所示:


#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:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<list<Node> > graph;
vector<int> re;
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());
re.push_back(graph[i].front().name);
}
}
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());
re.push_back(it->name);
}
}
}
if (que.empty()) {
if (count == graph.size()) {
return re;
}
else {
vector <int> false1;
return false1;
}
}

}


};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值