# Course-Schedule

Nov 18, 2017

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. Note: The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. You may assume that there are no duplicate edges in the input prerequisites.

2
3->8->9->10
5->11
7


def helper(self,v,visited,graph):
visited[v] = -1 #设置为访问中
for i in graph[v]:
if visited[i] == -1: #访问中
return False
if visited[i] == 0: #未访问
if self.helper(i,visited,graph) == False:
return False
visited[v] = 1 # 递归函数开始返回了，设置为已访问的状态
return True
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
visited = [0]*numCourses #初始时，所有节点都未访问
#将边集转化成邻接表
graph = [[] for i in range(numCourses)]
for e in prerequisites:
graph[e[0]].append(e[1])

#DFS
for i in range(numCourses):
if visited[i] == False:
if self.helper(i,visited,graph) == False:
return False

return True


dicuss中的BFS解法：

class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph = make_graph(numCourses, prerequisites);
vector<int> degrees = compute_indegree(graph);
for (int i = 0; i < numCourses; i++) {
int j = 0;
for (; j < numCourses; j++)
if (!degrees[j]) break;
if (j == numCourses) return false;
degrees[j] = -1;
for (int neigh : graph[j])
degrees[neigh]--;
}
return true;
}
private:
vector<unordered_set<int>> make_graph(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph(numCourses);
for (auto pre : prerequisites)
graph[pre.second].insert(pre.first);
return graph;
}
vector<int> compute_indegree(vector<unordered_set<int>>& graph) {
vector<int> degrees(graph.size(), 0);
for (auto neighbors : graph)
for (int neigh : neighbors)
degrees[neigh]++;
return degrees;
}
};


LeetCodeLeetCode

House Robber

Implement Trie(Prefix Tree)