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算法(第一个代码),邻接矩阵(前两个代码),邻接表(第三个代码))
- 判断是否存在哈密顿回路,DFS——zoj3526
- LeetCode 207. Course Schedule(拓扑排序-求有向图中是否存在环)
- Shell脚本执行hive语句 | hive以日期建立分区表 | linux schedule程序 | sed替换文件字符串 | shell判断hdfs文件目录是否存在
- CSU 1660 K-Cycle(dfs判断无向图中是否存在长度为K的环)
- 图结构练习——判断给定图是否存在合法拓扑序列
- js 如何判断Javascript对象是否存在
- SQLite Database判断是否存在、新建、删除.....
- 算法题:判断数组中是否存在重复出现的数
- Asp.Net判断文件是否存在
- c# list exists(contains) delegate 委托判断 元素是否在LIST中存在
- 判断文件夹是否存在并创建
- VB 判断文件是否存在
- Mybatis 实现Mysql批量插入数据,判断数据是否存在
- C#判断JObject成员key是否存在
- shell判断文件是否存在
- 如何判断一个list中是否存在重复值
- Python3基础 list in 与 not in 判断一个变量是否在列表中存在
- ADO access数据库 判断表是否存在
- C# 判断服务器上文件是否存在