Problem:207. Course Schedule
Question
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. Read more about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
思路
对于题目给定的课程,如果刚好在 prerequisites (我们称它为先导课程吧)中,则上这门课程的前提是先上了另一门课程。
最简单来说,就是你穿鞋子之前必须先穿袜子,顺序不能颠倒。
大学里,想上大二的课程,就必须先修完大一的课程。课程有一定的顺序,不能颠倒(当然也存在可以直接修读的课程)
题目给定的prerequisites是以一序列的数对出现的,我们把他表示为这种形式:
- 第一种情况
3, [[2,1], [0,1]]
我们用一个图来表示这种关系,如上图所示,箭头代表,上完某个课程(起点)才能去上另一个课程(终点)。在这个图我们可以发现,上了课程1(因为课程1没有任何要求),然后就可以上课程0和课程2,所有的课程都可以上完。另外,注意到,这个图是没有环路的,也即,从任意一点出发,不会通过某条路径再回到起点。
- 第二种情况
3, [[1, 0], [2, 1], [0, 2]]
同样用一个图来表示这种关系。在这个图中,最明显就是存在一个环路,我们来看看能否上完所有课程。假设我们先上课程1,但是很遗憾,必须先上课程0,那就先上课程0,然而必须上完课程2!!!
所以,无论从哪个课程开始上,必然都会导致死循环,就是哪一个课程都上不了,相互制约。一环套一环。
所以,根据上面的思考,加上对这个题目的理解,这个题实际上是在问你,一个有向图中是否存在环!我用DFS来求解
DFS深度优先遍历
解题代码
#include <vector>
#include <set>
#include <list>
#include <map>
#include <iostream>
using namespace std;
class Solution {
public:
bool flag = true;
map<int, list<int>> adjList;
set<int> visited;
set<int> marked;
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
for (auto pre : prerequisites) {
if (adjList.find(pre.first) == adjList.end()) {
list<int> newlist;
newlist.push_back(pre.second);
adjList[pre.first] = newlist;
}
else
adjList.find(pre.first)->second.push_back(pre.second);
}
for(auto pre : prerequisites) {
if (!flag)
return flag;
visit(pre.first, prerequisites);
}
return flag;
}
void visit(int course, vector<pair<int, int>>& prerequisites) {
visited.insert(course);
marked.insert(course);
if (adjList.find(course) != adjList.end())
for(auto a : adjList[course]) {
if (visited.find(a) == visited.end())
visit(a, prerequisites);
else if(marked.find(a) != marked.end())
flag = false;
}
marked.erase(course);
}
};