算法——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()函数进行了初始化和赋值。

猜你喜欢

转载自blog.csdn.net/melwx/article/details/85297185