这次的题目是Course Schedule...题目看起来好像很复杂,我也纠结了好久...但是实际上...并没有想象中那么复杂orz
207 | Course Schedule | 31.1% | Medium |
它是Graph分类里面的一道题,还有后续的Course Schedule II
题目介绍是这样子的:
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.
- This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
- Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
- Topological sort could also be done via BFS.
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
struct Node
{
int num;
vector<Node*> next;
int indegree;
bool ischeck;
Node(int n)
{
num=n;
ischeck=false;
indegree=0;
}
};
bool TopologicalSort(int numCourses,vector<Node*>& graph)
{
queue<Node*> list;
vector<Node*> sortedList;
int count;
for(int i=0;i<numCourses;i++)
{
if(graph[i]->indegree==0&&graph[i]->ischeck==false)
{
list.push(graph[i]);
}
}
while(list.size()>0)
{
Node* temp=list.front();
//cout<<"temp is "<<temp->num;
sortedList.push_back(list.front());
temp->ischeck=true;
//cout<<" "<<temp->num<<"'s ischeck is "<<temp->ischeck<<endl;
list.pop();
for(int i=0;i<temp->next.size();i++)
{
temp->next[i]->indegree--;
if(temp->next[i]->indegree==0)
{
list.push(temp->next[i]);
//cout<<"list pushback "<<temp->next[i]->num<<endl;
}
}
}
if(sortedList.size()==numCourses)
{
return true;
}
else
{
return false;
}
}
bool canFinish(int numCourses, vector<pair<int, int> >& prerequisites)
{
if(prerequisites.size()==0)
{
return true;
}
bool finish=true;
//queue<Node*> tocheck;
vector<Node*> graph;
for(int i=0;i<numCourses;i++)
{
Node* temp=new Node(i);
graph.push_back(temp);
}
int size=prerequisites.size();
for(int i=0;i<size;i++)
{
int first=prerequisites[i].first;
int second=prerequisites[i].second;
graph[second]->next.push_back(graph[first]);
graph[first]->indegree++;
}
finish=TopologicalSort(numCourses,graph);
return finish;
}
相比起DFS来,拓扑排序真的是太太太太太简单了...