1004. 无环图

来源:互联网 发布:测光表测出的数据调整 编辑:程序博客网 时间:2024/05/16 11:28
Description

 

在图论中,如果一个有向图从任意顶点出发无法经过若干条边回到该点,则这个图是一个有向无环图(Directed Acyclic Graph,DAG). 对于一个n个节点的有向图(节点编号从0到n-1),请判断其是否为有向无环图.
 
图的节点数和边数均不多于100000.
 
请为下面的Solution类实现解决上述问题的isDAG函数,函数参数中n为图的节点数,edges是边集,edges[i]表示第i条边从edges[i].first指向edge[i].second. 如果是有向无环图返回true,否则返回false.
 
class Solution {
public:
       bool isDAG(int n, vector<pair<int, int>>& edges) {
          
    }
};
 
例1:
n = 3,edges = {(0, 1), (0, 2)},函数应返回true.
 
例2:

n = 2,edges = {(0, 1), (1, 0)},函数应返回false.


题解:循环删除入度为0的点,如果结束循环后图中还有点存在则是有环图,否则是无环图。


class Solution {public:       bool isDAG(int n, vector<pair<int, int>>& edges) {          int num = n;          int point[100000]={0};          queue<int> queue1;          vector<vector<int>> vector1;          for(int i=0; i<n; i++){              vector<int>* vector2 = new vector<int>();              vector1.push_back(*vector2);          }          //记录每个点的入度          for(int i=0; i<edges.size(); i++){              pair<int, int> line = edges[i];              int start = line.first;              int end = line.second;              point[end]++;              vector1[start].push_back(end);          }          //查找入度为零的点          for(int i=0; i<n; i++){              if(point[i] == 0){                  queue1.push(i);                  num--;                  point[i] = -2;              }          }          while(!queue1.empty()){              int temp = queue1.front();              queue1.pop();              vector<int> vector3 = vector1[temp];              //删除与点temp为后继的点的入度              for(int i=0; i<vector3.size(); i++){                  int temp1 = vector3[i];                  if(point[temp1] != -2){                      point[temp1]--;                      if(point[temp1] == 0){                          num--;                          queue1.push(temp1);                          point[temp] = -2;                      }                  }              }          }          if(num == 0)               return true;          else               return false;       }};