Course Schedule

其實這道題目要求看似有難度,但反覆思考題目後會發現其實根本上只是利用深度搜索(DFS)以及拓譜排序尋找是否有環的出現以及主要在網上搜尋關於DFS檢測環的算法並參考,背景是關於課程的先後順序,譬如說在上高級編成之前要有C++的基礎等等,如果有出現則返回錯誤。

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.

首先先給出DFS的代碼段:

void dfs(int node, vector<vector<int>> &gragh, vector<int> &visited, bool &cycle) {
    if (visited[node] == 1) 
{
cycle = true;
return;
} // cycle occurs, break the dfs chain and all return
    visited[node] = 1; //searching
    for (int i = 0; i < gragh[node].size(); i++) 
{
        dfs(gragh[node][i], gragh, visited, cycle);
        if (cycle) return; 
    }
    visited[node] = 2; //Black Once finished.
}

第一個參數為兩個vector的應用,透過二維數組可以表示鄰接表;第二個參數代表是否有訪問過者個點的vector;第三個為環的判斷參數。

主要我們透過visited作為是否訪問過的證據,如果訪問到第二次則代表有環的存在,透過遞歸重複調用DFS的函數遍歷所有的節點。

再來給出關於題目的主函數:

bool canFinish(int numCourses, vector<pair<int, int>>& pre) {
    vector<vector<int>> gragh(numCourses);
    vector<int> visited(numCourses, 0); // White at initialization
    for (int i = 0; i < pre.size(); i++) {
        gragh[pre[i].second].push_back(pre[i].first);
    }
    bool cycle = false;
    for (int i = 0; i < numCourses; i++) {
        if (cycle) return false;
        if (visited[i] == 0) dfs(i, gragh, visited, cycle);
    }
    return !cycle;
}

在第一個循環中主要把pair<int, int>的目的表示成數組的對應,較方便去理解以以及編程;第二個循環開始進入DFS與環的檢測,如果visited為0則代表還未訪問過並進入DFS並重複調用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章