利用拓扑排序和并查集实现判断有向图和无向图是否有环

无向图-并查集实现

/**
 * 
 * @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));
	}
}

有向图:

不显示

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值