1. 程式人生 > >DFS解207. Course Schedule(判斷有向圖是否存在環)

DFS解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?

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.

For another example

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:

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.

題目解析

題目的背景是關於選修課的上課次序問題。給定n門課程,並且給了這些課程修的次序,判斷這些課程能否合理地修完。比如2門課程,[1,0]這一對說明要修1課程必須要修0課程,這樣的話2門課程就可以先修0課程,再修1課程,能夠合理修完。如果2門課程,[1,0],[0,1]說明修1課程必須要修0課程,修0課程必須要修1課程,那麼無論怎麼修,都不能滿足條件,因此這2門課程不能合理修完

思路分析

這就是很簡單的圖論判斷有向圖是否有環的問題。我們可以對其中的節點分3種狀態。0表示這個節點沒有被遍歷,-1表示這個節點正在被遍歷,1表示這個節點已經被遍歷完畢,如果有2個節點之間有邊,並且兩個節點的狀態相等,那麼就說明在這個有向圖中存在環

AC程式碼

#include <iostream>
#include <memory.h>
#include <vector>
#include <set>
using namespace std;
int a[2000][2000], visit[2000];
bool is_ascylic;
class Solution {
public:
    void dfs(int sp, int ep) {
        visit[sp] = -1;
        for (int i = 0; i < ep; ++i) {
            if (a[sp][i] == 1 && visit[i] == 0) {
                dfs(i, ep);
                visit[i] = 1;
            }
            if (a[sp][i] == 1 && visit[i] == -1) {
                is_ascylic = true;
                return;
            }
        }
    }
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        is_ascylic = false;
        set<int> appear_num;
        memset(a, 0, sizeof(a));
        memset(visit, 0, sizeof(visit));
        int len = prerequisites.size();
        for (int i = 0; i < len; ++i) {
            a[prerequisites[i].first][prerequisites[i].second] = 1;
            appear_num.insert(prerequisites[i].first);
        }
        for (int i = 0; i < numCourses; ++i) {
            if (!visit[i]) {
                dfs(i, numCourses);
                visit[i] = 1;
            }
        }
        return !is_ascylic;
    }
};
int main() {
    Solution s;
    pair<int, int> pp(1, 0);
    pair<int, int> ppp(0, 1);
    vector<pair<int, int>> vpp;
    vpp.push_back(pp);
    vpp.push_back(ppp);
    std::cout << s.canFinish(3, vpp) << std::endl;
    return 0;
}