您的位置:首页 > 其它

DFS解207. Course Schedule(判断有向图是否存在环)

2017-09-23 20:42 309 查看

题目

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.

For another example

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:

1.The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

2.You may assume that there are no duplicate edges in the input prerequisites.

题目解析

题目的背景是关于选修课的上课次序问题。给定n门课程,并且给了这些课程修的次序,判断这些课程能否合理地修完。比如2门课程,[1,0]这一对说明要修1课程必须要修0课程,这样的话2门课程就可以先修0课程,再修1课程,能够合理修完。如果2门课程,[1,0],[0,1]说明修1课程必须要修0课程,修0课程必须要修1课程,那么无论怎么修,都不能满足条件,因此这2门课程不能合理修完

思路分析

这就是很简单的图论判断有向图是否有环的问题。我们可以对其中的节点分3种状态。0表示这个节点没有被遍历,-1表示这个节点正在被遍历,1表示这个节点已经被遍历完毕,如果有2个节点之间有边,并且两个节点的状态相等,那么就说明在这个有向图中存在环

AC代码

#include <iostream>
#include <memory.h>
#include <vector>
#include <set>
using namespace std;
int a[2000][2000], visit[2000];
bool is_ascylic;
class Solution {
public:
void dfs(int sp, int ep) {
visit[sp] = -1;
for (int i = 0; i < ep; ++i) {
if (a[sp][i] == 1 && visit[i] == 0) {
dfs(i, ep);
visit[i] = 1;
}
if (a[sp][i] == 1 && visit[i] == -1) {
is_ascylic = true;
return;
}
}
}
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
is_ascylic = false;
set<int> appear_num;
memset(a, 0, sizeof(a));
memset(visit, 0, sizeof(visit));
int len = prerequisites.size();
for (int i = 0; i < len; ++i) {
a[prerequisites[i].first][prerequisites[i].second] = 1;
appear_num.insert(prerequisites[i].first);
}
for (int i = 0; i < numCourses; ++i) {
if (!visit[i]) {
dfs(i, numCourses);
visit[i] = 1;
}
}
return !is_ascylic;
}
};
int main() {
Solution s;
pair<int, int> pp(1, 0);
pair<int, int> ppp(0, 1);
vector<pair<int, int>> vpp;
vpp.push_back(pp);
vpp.push_back(ppp);
std::cout << s.canFinish(3, vpp) << std::endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dfs 算法