无向图-并查集实现
/**
*
* @author FJX
*利用并查集判断无向图中是否有环
*/
public class Solution {
public int[] parent;//记录并查集元素父节点
public int depth[];//记录并查集每个元素的深度
//初始化操作
public Solution(int nums) {
this.parent = new int[nums];
this.depth = new int[nums];
for(int i = 0;i<nums;i++) {
parent[i] = -1;
}
}
public int find_root(int x) {//查找x的代表元素
int root = x;
while(parent[root]!=-1) {
root = parent[root];
}
return root;
}
public boolean union(int x,int y) {
int x_root = find_root(x);
int y_root = find_root(y);
if(x_root == y_root) {
return false;//说明有环
}else {
if(depth[x_root]>depth[y_root]) {//如果x_root树更深,则把y_root加到x_root上
parent[y_root] = x_root;
}else if(depth[x_root]<depth[y_root]) {//如果y_root树更深,则把x_root加到y_root上
parent[x_root] = y_root;
}else if(depth[x_root] == depth[y_root]) {//相等的情况下,加到哪个都行,相应的数深+1
parent[x_root] = y_root;
depth[x_root]++;
}
}
return true;
}
public static void main(String[] args) {
int[][] rec = {//邻接矩阵
{0,1,0,0,0},
{1,0,1,0,1},
{0,1,0,1,0},
{0,0,1,0,0},
{0,1,0,0,0}
};
Solution s = new Solution(5);
for(int i = 0;i<rec.length;i++) {
for(int j = 0;j<i;j++) {
if(rec[i][j] == 1) {
boolean b = s.union(i, j);
if(b == false ) {
System.out.println("有环");
return;
}
}
}
}
System.out.println("没有环");
}
}
有向图-拓扑排序
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Solution {
/**
* rect是邻接矩阵,nums代表图中元素的个数
*/
public static boolean cycle(List<List<Integer>> rect,int nums) {
int count = nums;//计数器
int[] indegree = new int[nums];//各个节点的入度数组
//统计各个节点的入度
for(int i = 0;i<rect.size();i++) {
for(int j = 0;j<rect.get(i).size();j++) {
indegree[rect.get[i].get(j)]++;
}
}
Queue<Integer> queue = new LinkedList<>();
//把入度为0的节点加入队列
for(int i = 0;i<nums;i++) {
if (indegree[i] == 0) {
queue.add(i);
}
}
while(!queue.isEmpty()) {
int i = queue.poll();//弹出一个入队为0的元素
count--;//元素个数-1
//以i为前驱的节点入度-1
for(Integer c:rect.get(i)) {
if(--indegree[c] == 0) {
queue.add(c);
}
}
}
return count == 0;
}
public static void main(String[] args) {
List<List<Integer>> rect = new ArrayList<List<Integer>>();
rect.add(new ArrayList<Integer>(Arrays.asList(1,2)));
rect.add(new ArrayList<Integer>(Arrays.asList(3)));
rect.add(new ArrayList<Integer>());
rect.add(new ArrayList<Integer>(Arrays.asList(0)));
System.out.println(cycle(rect, 4));
}
}
有向图: