【Leetcode】Course Schedule #207

来源:互联网 发布:域名备案ps 编辑:程序博客网 时间:2024/05/16 06:22

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.


一道拓扑排序题,不知道为什么Leetcode一些测试通不过,但是在本地测试那些cases都可以通过

enum Status {Unvisited = 0, Temp_Visited, Visited};void constructGraph(int numCourses, vector<pair<int, int>> &prerequisites, unordered_map<int, vector<int>> &graph) {  unsigned long size = prerequisites.size();  for (int i = 0; i < size; ++i)    graph[prerequisites[i].first].push_back(prerequisites[i].second);}bool topo_sort_helper(int target, unordered_map<int, vector<int>> &graph, int *visit_record) {  if(visit_record[target] == Visited) return true;  else if (visit_record[target] == Temp_Visited) return false;  else {    visit_record[target] = Temp_Visited;    bool topo_success = false;    vector<int> connected_edge = graph[target];    unsigned long num_of_edges = connected_edge.size();    for (int i = 0; i < num_of_edges; ++i)    {      topo_success = topo_sort_helper(connected_edge[i], graph, visit_record);      if (topo_success == false) return false;    }    visit_record[target] = Visited;    return true;  }}bool topo_sort(int numCourses, unordered_map<int, vector<int>> &graph) {  int *visit_record = new int[numCourses];  memset(visit_record, Unvisited, numCourses);  for (int i = 0; i < numCourses; ++i)  {    if (visit_record[i] == Visited) continue;    else if (visit_record[i] == Unvisited) {      if (topo_sort_helper(i, graph, visit_record) == false)      {        delete visit_record;        return false;      }    }  }  delete visit_record;  return true;}bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {  unordered_map<int, vector<int>>  graph;  constructGraph(numCourses, prerequisites, graph);  return topo_sort(numCourses, graph);}


0 0