Geeks - Union-Find Algorithm - Detect Cycle in a an Undirected Graph算法
来源:互联网 发布:网络流行语来源及意思 编辑:程序博客网 时间:2024/05/22 10:31
利用Union Find的方法查找图中是否有环。
在于构建一个图数据结构,和一般图的数据结构不同的是这个图是记录了边的图,并在查找过程中不断把边连接起来,形成一个回路。
原文地址:
http://www.geeksforgeeks.org/union-find/
#pragma once#include <stdio.h>#include <stdlib.h>#include <string.h>#include <algorithm>class UnionFind{struct Edge{int src, des;explicit Edge(int s = 0, int d = 0) : src(s), des(d) {}};struct Graph{int V, E; // V-> Number of vertices, E-> Number of edgesEdge *edges;Graph(int v, int e) : V(v), E(e), edges(new Edge[e]){}~Graph(){if (edges) delete [] edges;}};int find(int parent[], int i){if (-1 == parent[i]) return i;return find(parent, parent[i]);}void unionTwo(int parent[], int x, int y){int xset = find(parent, x);int yset = find(parent, y);parent[xset] = yset;}bool isCycle(Graph *gra){int *parent = (int *) malloc (gra->V * sizeof(int));std::fill(parent, parent+gra->V, -1);for (int i = 0; i < gra->E; i++){int x = find(parent, gra->edges[i].src);int y = find(parent, gra->edges[i].des);if (x == y) return true;unionTwo(parent, x, y);}return false;}public:UnionFind(){Graph *gra = new Graph(3, 3);gra->edges[0].src = 0;gra->edges[0].des = 1;gra->edges[1].src = 1;gra->edges[1].des = 2;gra->edges[2].src = 0;gra->edges[2].des = 2;if (isCycle(gra))printf( "Graph contains cycle\n" );elseprintf( "Graph doesn't contain cycle\n" );delete gra;}};
1 0
- Geeks - Union-Find Algorithm - Detect Cycle in a an Undirected Graph算法
- Detect cycle in an undirected graph
- Geeks - Detect Cycle in a Directed Graph 判断图是否有环
- Geeks Union-Find Algorithm Union By Rank and Path Compression 图环算法
- Detect Cycle in a linked list (Floyd’s Cycle Detection Algorithm)
- [leetcode323]Number of Connected Components in an Undirected Graph
- LeetCode 323. Number of Connected Components in an Undirected Graph
- leetcode Number of Connected Components in an Undirected Graph
- Number of Connected Components in an Undirected Graph
- Leetcode 323. Number of Connected Components in an Undirected Graph
- LeetCode 323. Number of Connected Components in an Undirected Graph
- LeetCode 323. Number of Connected Components in an Undirected Graph
- Leetcode 323. Number of Connected Components in an Undirected Graph
- No323. Number of Connected Components in an Undirected Graph
- 323. Number of Connected Components in an Undirected Graph
- leetcode323. Number of Connected Components in an Undirected Graph
- Find the Connected Component in the Undirected Graph
- judge loop in undirected graph
- 为编写的Windows程序提升权限
- treeview节点拖动
- 下一代游戏主机,8GB内存怎么够
- 【机器学习算法-python实现】KNN-k近邻算法的实现(附源码)
- 北京地区的图像处理公司
- Geeks - Union-Find Algorithm - Detect Cycle in a an Undirected Graph算法
- HTML_form应用
- 序列操作 && 小气的小B(tyvj 1491 && 1297)
- android 判断wifi是否已经连接
- 【机器学习算法-python实现】逻辑回归的实现(LogicalRegression)
- 汽车合同纠纷案例之拖延交货
- Andriod Fragment 的作用和基本用法
- 【CSDN社区专栏】JEECG微云快速开发平台应用与案例
- 像素完美碰撞检测(使用cocos2d-x)