题目:Course Schedule
链接:https://leetcode.com/problems/course-schedule/#/description
原题:
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.
解题思路:
本题使用暴力的深搜思路,先把限制条件用合适的容器存起来,然后将不受任何条件限制的课程进队列,用while循环遍历队列的每一门课程,并且将修过课程对别的课程的限制去掉,如果某一课程的限制被去掉变为零后,便可入队,如此循环得到答案。
代码:
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<bool> taked_course;
vector<int> all_course;
map<int, vector<int>> limit;
for(int i=0; i<numCourses; i++) {
taked_course.push_back(false);
all_course.push_back(i);
}
queue<int> course_list;
vector<pair<int, int>>::iterator it;
for(it=prerequisites.begin(); it!=prerequisites.end(); it++) {
if(limit.count((*it).second) != 0) {
limit[(*it).second].push_back((*it).first);
} else {
vector<int> temp_vec;
temp_vec.push_back((*it).first);
limit[(*it).second] = temp_vec;
}
vector<int>::iterator find_loc = find(all_course.begin(), all_course.end(), (*it).second);
if(find_loc != all_course.end()) {
all_course.erase(find_loc);
}
}
if(all_course.empty()) {
return false;
}
for(vector<int>::iterator itt=all_course.begin(); itt!=all_course.end(); itt++) {
course_list.push(*itt);
}
while(!course_list.empty()) {
int course_id = course_list.front();
taked_course[course_id] = true;
for(it=prerequisites.begin(); it!=prerequisites.end(); it++) {
if((*it).first == course_id) {
vector<int>::iterator find_loc = find(limit[(*it).second].begin(), limit[(*it).second].end(), (*it).first);
limit[(*it).second].erase(find_loc);
if(limit[(*it).second].empty()) {
course_list.push((*it).second);
prerequisites.erase(it);
it--;
}
}
}
course_list.pop();
}
if(find(taked_course.begin(), taked_course.end(), false) != taked_course.end()) {
return false;
} else {
return true;
}
}
};