• [Leetcode] Course Schedule


    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.

    click to show more hints.

    拓扑排序。用一个队列存入度为0的节点,依次出队,将与出队节点相连的节点的入度减1,如果入度减为0,将其放入队列中,直到队列为空。如里最后还有入度不为0的节点的话,说明有环,否则无环。

     1 class Solution {
     2 public:
     3     bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
     4         vector<vector<int>> graph(numCourses, vector<int>(0));
     5         vector<int> inDegree(numCourses, 0);
     6         for (auto u : prerequisites) {
     7             graph[u[1]].push_back(u[0]);
     8             ++inDegree[u[0]];
     9         }
    10         queue<int> que;
    11         for (int i = 0; i < numCourses; ++i) {
    12             if (inDegree[i] == 0) que.push(i);
    13         }
    14         while (!que.empty()) {
    15             int u = que.front();
    16             que.pop();
    17             for (auto v : graph[u]) {
    18                 --inDegree[v];
    19                 if (inDegree[v] == 0) que.push(v);
    20             }
    21         }
    22         for (int i = 0; i < numCourses; ++i) {
    23             if (inDegree[i] != 0) return false;
    24         }
    25         return true;
    26     }
    27 };
  • 相关阅读:
    【hihocoder 1477】闰秒
    【codeforces 768F】Barrels and boxes
    【codeforces 767E】Change-free
    【codeforces 810A】Straight «A»
    【codeforces 810B】Summer sell-off
    【codeforces 810C】Do you want a date?
    【codeforces 757E】Bash Plays with Functions
    【codeforces 749D】Leaving Auction
    Java数据结构与算法(5)
    使用Xshell远程连接管理Linux实践
  • 原文地址:https://www.cnblogs.com/easonliu/p/4483437.html
Copyright © 2020-2023  润新知