判断图是否有环——DFS另类解法

判断图是否有环——DFS另类解法

首先对每个结点进行一次DFS遍历,记录所遍历的结点数,取最小值,记作count。

根据count判断是否为连通图:

如果是,直接根据结点数和边数的关系就可判断(边数大于等于结点数则必有回路)

如果不是,若 count + 图的边数 >= 图的结点数,则必存在回路(画图试出来的,这里count必须取最小值,否则判断错误)

Java代码

	static class MGraph {
		int vexnum;
		int arcnum;
		boolean[][] Edge;

		MGraph(int vex, int arc) {
			vexnum = vex;
			arcnum = arc;
			Edge = new boolean[vexnum + 1][vexnum + 1];
		}
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int n = input.nextInt(); // 结点数
		int m = input.nextInt(); // 边数
		MGraph graph = new MGraph(n, m);
		for (int i = 0; i < m; i++) { // 所有边
			int x = input.nextInt();
			int y = input.nextInt();
			graph.Edge[x][y] = graph.Edge[y][x] = true;
		}
		boolean[] visited = new boolean[n + 1];

		int count = Integer.MAX_VALUE;
		int res = 0;
		for(int i = 1; i <= n; i++) {
			res = DFS(graph, i, visited, 0);
			count = Integer.min(count, res);
		}
		if(count == graph.vexnum && graph.arcnum >= count)
			System.out.println("YES");
		else if(count < graph.vexnum && count + graph.arcnum >= graph.vexnum)
			System.out.println("YES");
		else
			System.out.println("NO");
	}

	public static int DFS(MGraph graph, int v, boolean[] visited, int count) {
		visited[v] = true;
		count++;
		for (int i = 1; i <= graph.vexnum; i++) {
			if (graph.Edge[v][i] == true && !visited[i])
				return DFS(graph, i, visited, count);
		}
		return count;
	}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值