207. Course Schedule
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.
解题思路:
每门课程看作一个顶点,课程之间的关系可以看作是一个有向图,如果有关系[1,0],即说明从0到1有一条边。判断一个人是否能修完所有的课,即为判断该图中是否有环。即判断改图是否为DAG,可以使用dfs。
代码展示:
class Solution {
public:
void dfs(int s , vector<int> G[],int vis[])
{
vis[s]=-1;
for(int i=0;i<G[s].size();i++)
{
if(vis[G[s][i]]==-1)
{
isDag = false;
return;
}
else if(vis[G[s][i]]==0)
{
dfs(G[s][i],G,vis);
}
}
vis[s]=1;
}
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
int n = prerequisites.size();
isDag = true;
vector<int> G[numCourses];
for(int i=0;i<n;i++)
{
pair<int,int> tmp=prerequisites[i];
G[tmp.second].push_back(tmp.first);
}
int vis[numCourses];
for(int i=0;i<numCourses;i++) vis[i]=0;
//vis[0]=-1;
//dfs(0,G,vis);
for(int i=0;i<numCourses;i++)
{
if(vis[i]==0)
{
dfs(i,G,vis);
}
}
return isDag;
}
bool isDag;
};