Leetcode 207/210. Course Schedule I/II

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.

在這裏插入圖片描述

method 1 topological sort

有嚴格的順序要求,所以自然而然想到拓撲排序
輸入的是邊集,所以要建圖纔好使用拓撲排序,這裏選擇鄰接表作爲圖的數據結構(聲明一個vector的二維數組vector<vector> edge(numCourses);)
使用隊列進行BFS搜索,進行拓撲排序

vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
    vector<vector<int>> edge(numCourses);

	int* indegree = new int[numCourses];
	for (int i = 0; i < numCourses; i++)
		indegree[i] = 0;

	for (int i = 0; i < prerequisites.size(); i++)
	{
		indegree[prerequisites[i][0]]++;
		edge[prerequisites[i][1]].push_back(prerequisites[i][0]);
	}

	queue<int> q; //保存入度爲0的結點
	for (int i = 0; i < numCourses; i++)
	{
		if (indegree[i] == 0)
			q.push(i);
	}

	vector<int> ans;
	while (!q.empty())
	{
		int v = q.front(); q.pop();
		ans.push_back(v);
		for (int i = 0; i < edge[v].size(); i++)
		{
			if (--indegree[edge[v][i]] == 0)
				q.push(edge[v][i]);
		}
	}

    if(ans.size() < numCourses) ans.clear();
	return ans;
    }

如果ans的大小小於節點個數,說明存在環

summary

  1. 有嚴格的順序要求,使用BFS建立拓撲排序
  2. 本題拓撲排序是模板代碼,需要牢記
發佈了93 篇原創文章 · 獲贊 9 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章