LeetCode#210 Course Schedule II(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, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

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 the correct course order is [0,1]

4, [[1,0],[2,0],[3,1],[3,2]]

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].

題意解讀:

該題比較好理解,就是拓撲排序,若輸出的結點數小於頂點數,則圖有環輸出空字符串,反之輸出一個拓撲序,一下是廣度優先遍歷的c++實現版

class Solution {
public:
    vector<int> findOrder(int numCourse, vector<pair<int, int> >& prerequisite) {
    	numCourses = numCourse; 
    	prerequisites = prerequisite;
    	//計算入度的函數 
    	find_In_degree();
    	//拓撲排序的函數 
    	find_topo_sort();
    	if(topo_sort.size() == numCourses)
    	return topo_sort;
    	else return {};
    }
    void find_In_degree() {
    	for(int i = 0; i < numCourses; i++) {
    		in_degree.push_back(0);
		}
    	vector<pair<int,int> >::iterator it;
    	for(it = prerequisites.begin(); it != prerequisites.end(); it++) {
    		in_degree[it->first]++;
		}
	}
	void find_topo_sort() {
		int zeros = -1;
		for(int i = 0; i < numCourses; i++) {
			zeros = -1;
			//尋找入度爲0的點 
			for(int j = 0; j < numCourses; j++) {
				if(in_degree[j] == 0) {
					zeros = j;
					break;
				}
			}
			//找到入度爲0的點後,把所有與該結點相連的邊 刪掉 
			if(zeros != -1) {
			topo_sort.push_back(zeros);
			in_degree[zeros] = -1;
			vector<pair<int,int> >::iterator it;
			for(it = prerequisites.begin(); it != prerequisites.end(); it++) {
    			if(it->second == zeros) {
    				in_degree[it->first]--;
    			}
			}
			}
		}
	}
private:
	int numCourses;
	vector<pair<int, int> > prerequisites;
	vector<int> in_degree;
    vector<int> topo_sort;
};


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