Leetcode 207. Course Schedule

xiaoxiao2021-02-28  99

题目:

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.

思路:拓扑排序,用floyd尝试了一下,主要是回忆一下怎么写。复杂度太高跑不完。最后用拓扑可以。 //floyd class Solution { public: bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { vector<vector<int>> map(numCourses,vector<int>(numCourses,10000)); //10000是设置的一个最大边长值 for(int i = 0; i < prerequisites.size(); i++){ map[prerequisites[i].first][prerequisites[i].second] = 1; } vector<vector<int>> d = map; int n = numCourses; vector<vector<int>> tmp = d; for(int k = 0; k < n; k++){ vector<vector<int>> tmp = d; for(int i = 0; i < n; i++) for(int j = 0; j < n;j++) tmp[i][j] = min(d[i][j],d[i][k]+d[k][j]); d = tmp; } for(int i = 0; i < n;i++){ for(int j = i+1; j < n; j++){ if(d[i][j] != 10000&&d[j][i] !=10000) return false; } } return true; } };拓扑排序;

class Solution { public: bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { if(numCourses == 0) return false; vector<int> indegree(numCourses, 0); unordered_map<int, multiset<int>> hash; for(auto val: prerequisites) { indegree[val.first]++; hash[val.second].insert(val.first); } for(int i = 0, j; i < numCourses; i++) { for(j = 0; j < numCourses; j++) if(indegree[j]==0) break; if(j==numCourses) return false; indegree[j]--; for(auto val: hash[j]) indegree[val]--; } return true; } };

转载请注明原文地址: https://www.6miu.com/read-38956.html

最新回复(0)