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; }};
阅读全文
0 0
- 1004. 无环图
- 1004.无环图
- 1004. 无环图
- 【Sicily】1004. 无环图
- 算法期中1004. Kahn算法求解有向无环图拓扑排序
- 【1004】无环图
- 1004. 奖金
- 1004.Median
- 1004. Hashing
- 1004. 成绩排名
- 1004. 成绩排名
- 1004. 成绩排名
- 1004.成绩排名
- 1004. 成绩排名
- 1004. 成绩排名
- 1004. 成绩排名
- 1004. 成绩排名
- 1004. 成绩排名
- mysql技巧之数据去重并记录总数
- 知道创宇研发技能表v3.1
- AD10利用SMART PDF打印PCB文件(供华龙焊板子参考)
- RatingBar评分控件使用笔记
- hello world
- 1004. 无环图
- 美团CodeM 初赛 A伦 合并回文子串 区间dp
- Git 版本控制
- 环信透传消息
- sql,select拼接||,小数,前面的0不见了
- C语言基本数据类型
- mongodb知识总结
- 《机器学习》基本术语标准翻译总结:第1章
- Permutations II解法代码的解释