[LeetCode] Course Schedule,leetcodeschedule

來源:互聯網
上載者:User

[LeetCode] Course Schedule,leetcodeschedule

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.

解題思路:

這道題可以轉換成判斷一個有向圖是否有環,若有環,則不能完成,否則能完成。現將課程表示成一個有向圖,用鄰接表來儲存。然後通過DSF來遍曆圖,若存在一個節點被訪問了兩次,則表明有環。

注意到這個圖可能不是全連通圖,所以,需要將每個節點作為開始節點來驗證。為了減少遍曆次數,用數組mark來記錄以某個節點起始的節點進行深度遍曆是否有環。下面是代碼:

class Solution {public:    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {        int len=prerequisites.size();        if(len==0){            return true;        }        vector<vector<int>> graph(numCourses, vector<int>());   //鄰接表表示的圖        for(int i=0; i<len; i++){            graph[prerequisites[i][0]].push_back(prerequisites[i][1]);        }        bool visit[numCourses];  //是否已經訪問過        memset(visit, 0, numCourses * sizeof(bool));        bool mark[numCourses];  //是否已經驗證過該節點        memset(mark, 0, numCourses * sizeof(bool));                for(int i=0; i<numCourses; i++){            if(DFSHasCircle(graph, visit, mark, i)){                return false;            }        }        return true;    }        //判斷是否有環,思路為若存在一個節點訪問了2次,則表明有環    bool DFSHasCircle(vector<vector<int>>& graph, bool* visit, bool* mark, int current){        if(visit[current]){            return true;        }        if(mark[current]){            return false;        }        visit[current] = true;      //標記已經訪問過                for(int i=0; i<graph[current].size(); i++){            if(DFSHasCircle(graph, visit, mark, graph[current][i])){                return true;            }        }                mark[current] = true;       //表示以該頂點開始的可達的所有節點構成的子圖均沒有環        visit[current] = false;     //去掉已經訪問過的標記        return false;    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.