LeetCode207 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:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. You may assume that there are no duplicate edges in the input prerequisites.

思路:

    这道题其实就是看学习的课程之间时候存在环路,如果存在环路那么就不能完成学习。我们这里使用深度优先搜索判断时候存在环路:如果从一个点出发开始深度优先遍历,那么之后再次访问到该点,就说明有环出现了。

代码如下:

class Solution {
public:
    vector<vector<int>> admat; // 存储邻接矩阵
    vector<int> states;  //0表示没有被访问过
    void genAdmat(const int &nodeNum, const vector<pair<int, int>> &sites){
        admat = vector<vector<int>>(nodeNum, vector<int>(nodeNum, 0));
        for(pair<int, int> site:sites){
            admat[site.first][site.second] = 1;
        }
    }
    // 深度优先遍历
    bool hasloop = false;
    void DFS(int node){
        states[node] = 1;  //1表示是初始访问节点
        int nodeNum = int(states.size());
        for(int i = 0;i<nodeNum;i++){
            if(admat[node][i] != 0){
                if(states[i] == 1) {hasloop = true; break;}  //发现已经遍历过的节点,说明有环
                else if(states[i] == -1) continue;
                else DFS(i);
            }
        }
        states[node] = -1;  //表示已经被访问过了
    }
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        genAdmat(numCourses, prerequisites);
        states = vector<int>(numCourses, 0);
        for(int i = 0;i<numCourses;i++){
            if(states[i] == -1) continue;
            DFS(i);
            if(hasloop) return false;  //如果存在环则不能修完
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/88992495