1. 程式人生 > >演算法——Week10

演算法——Week10

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?

Example 1:

Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.

Example 2:

Input: 2, [[1,0],[0,1]]
Output: false
Explanation: 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.

解題思路
題目的本質是判斷有向圖中是否有環(不是所有點是否可達),如果有環則返回flase,無環返回true。解題時,我選擇用拓撲排序來判斷是否有環路存在。其基本思想是,選擇圖中所有入度為0的頂點,從圖中刪除該頂點和所有以它為起點的有向邊(這些有向邊的終點的入度-1)。如果最終圖為空,則無環,否則有環。


程式碼如下:

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        graph.resize(numCourses);
        tag.resize(numCourses);
        vector<int> in_degree(numCourses, 0);
        for(int i = 0; i < prerequisites.size(); i++) {
            int first = prerequisites[i].first;
            int second = prerequisites[i].second;
            graph[second].push_back(first);
            in_degree[prerequisites[i].first]++;
        }
        bool exist = true;
        vector<int> zero_degree;
        for(int i = 0; i < numCourses; i++) {
            if(in_degree[i] == 0) {
                zero_degree.push_back(i);
            }
        }
        if(zero_degree.size() == 0) {
            exist = false;
            return exist;
        }
        queue<int> q;
        for(int i = 0; i < zero_degree.size(); i++) {
            q.push(zero_degree[i]);
        }
        int count = 0;
        while(q.size() != 0) {
            int v = q.front();      // 從佇列中取出一個頂點
            q.pop();
            ++count;
            for(int i = 0; i < graph[v].size(); i++) {
                in_degree[graph[v][i]] = in_degree[graph[v][i]] - 1;
                if(in_degree[graph[v][i]] == 0) {
                    q.push(graph[v][i]);
                }
            }
        }
        if(count != numCourses) {
            exist = false;
        }
        return exist;
    }
private:
    vector<vector<int>> graph;
    vector<int> tag;
};

注:
c++中的二維向量初始化要注意。我是先定義了一個空二維向量,再使用之前用resize()函式進行了初始化和賦值。