zoukankan      html  css  js  c++  java
  • leetcode 207. 课程表

    判断有向无环图DAG  用拓扑排序

    统计每个节点的入度数和他的邻接节点。然后将入度为0的节点入队列,每出一个就把他的邻接节点的入度数减一。每出一个就把节点数量减一,最后判断其是否为0

     1 class Solution {
     2 public:
     3     bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
     4         vector<int> ins(numCourses,0); //入节点数组
     5         vector<vector<int>> neighbor(numCourses);//每个节点的邻接节点
     6         for(int i=0;i<prerequisites.size();i++)
     7         {
     8             ins[prerequisites[i][0]]+=1;
     9             neighbor[prerequisites[i][1]].push_back(prerequisites[i][0]);
    10         }
    11         queue<int> nodes;
    12         for(int i=0;i<numCourses;i++)
    13         {
    14             if(ins[i]==0)
    15             {
    16                 nodes.push(i);
    17             }
    18         }
    19         int count=numCourses;
    20         while(!nodes.empty())
    21         {
    22             int node=nodes.front();
    23             nodes.pop();
    24             count-=1;
    25             for(int i=0;i<neighbor[node].size();i++)
    26             {
    27                 ins[neighbor[node][i]]-=1;
    28                 if(ins[neighbor[node][i]]==0)
    29                 {
    30                     nodes.push(neighbor[node][i]);
    31                 }
    32             }
    33         }
    34         return count==0;
    35     }
    36 };
    每天进步一点点~
  • 相关阅读:
    16款值得一用的iPhone线框图模板 (PSD & Sketch)
    设计神器
    {CF812}
    hiho1080(多标记线段树)
    {容斥原理}
    {dp入门}
    {AC自动机}
    CF807
    Trie树
    杂记
  • 原文地址:https://www.cnblogs.com/libin123/p/14626266.html
Copyright © 2011-2022 走看看