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.

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

Analyse: Using BFS. 

 1 class Solution {
 2 public:
 3     bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
 4         if(prerequisites.empty()) return true;
 5         
 6         int n = prerequisites.size();
 7         vector<vector<bool> > graph(numCourses, vector<bool>(numCourses, false));
 8         vector<int> indegree(numCourses, 0);
 9         for(int i = 0; i < n; i++){
10             if(graph[prerequisites[i].second][prerequisites[i].first] == false){//avoid duplicate pairs
11                 graph[prerequisites[i].second][prerequisites[i].first] = true;
12                 indegree[prerequisites[i].first]++;
13             }
14         }
15         stack<int> stk;
16         int count = 0;
17         for(int i = 0; i < numCourses; i++){
18             if(indegree[i] == 0)
19                 stk.push(i);
20         }
21         while(!stk.empty()){
22             int source = stk.top();
23             stk.pop();
24             count++;
25             for(int i = 0; i < numCourses; i++){
26                 if(graph[source][i]){
27                     indegree[i]--;
28                     if(indegree[i] == 0)
29                         stk.push(i);
30                 }
31             }
32         }
33         return count == numCourses;
34     }
35     //1. construct a graph and compute each node's indegree
36     //2. push all nodes with 0 indegree to a stack
37     //3. pop out the first node, decrease its neighbour's degree by 1
38     //   push all nodes with 0 indegree to a stack and continue
39 };
原文地址:https://www.cnblogs.com/amazingzoe/p/5197015.html