[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; }};