您的位置:首页 > 其它

【LeetCode 207】Course Schedule

2015-06-16 14:46 337 查看
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.

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices.

思路:

此题可抽象为有向图中的环检测问题。常规解法为构建邻接矩阵或邻接链表后通过拓扑排序检测有向图中是否存在环路来解决。若存在环路说明这个小朋友悲剧了,即将面临辍学的危机,否则,小朋友就可以任性的选课直到毕业(然而事实上即使能顺利毕业也并没有什么*用)。

在这里使用了两个set容器数组来构建图(考虑到也许会有重复输入等情况,还有就是懒 - -!),随后进行拓扑排序求得结果。

class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int> >& prerequisites) {

const int n = numCourses;
int cnt = 0;

set<int> sets
, grap
;
queue<int> Queue;//队列,拓扑排序必备

//从给定的输入中构建图,sets[i]表示学习课程i后才能继续学习的后置课程的集合
//grap[i]表示学习课程i所必须的前置课程的集合(入度)
vector<pair<int, int> >::iterator it = prerequisites.begin();
for(; it != prerequisites.end(); it++)
{
sets[(*it).second].insert((*it).first);
grap[(*it).first].insert((*it).second);
}

//将不需要前置课程的课程(入度为0的课程)压入队列
for(int i = 0; i < n; i++)
if(grap[i].size() == 0)
Queue.push(i);

while(!Queue.empty())
{
//取出队首的课程
int cur = Queue.front();
Queue.pop();

//遍历当前课程(cur)的后置课程集合
//在每一个后置课程(*it)的前置课程的集合(grap[*it])中去掉当前课程
//若去掉当前课程后该课程的前置课程集合为空,则将其压入队列
set<int>::iterator it = sets[cur].begin();
for(; it != sets[cur].end(); it++)
{
grap[*it].erase(cur);
if(grap[*it].size() == 0)
Queue.push(*it);
}
cnt++;//统计共拓扑出了多少课程
}

//若拓扑出的课程数等于总课程数,说明无环,return true,反之,return false
return cnt == n ? 1 : 0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: