并查集。。。

本文介绍了如何使用Java实现一个Solution类,通过深度优先搜索(DFS)判断给定无向图中,从source节点到destination节点是否存在路径,同时涉及了带权平均、rank值处理和路径压缩的方法。
摘要由CSDN通过智能技术生成

带权平均

把根节点挂在rank值大的节点上

rank值相等取左边

路径压缩:

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

class Solution { public boolean validPath(int n, int[][] edges, int source, int destination) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<Integer>(); } for (int[] edge : edges) { int x = edge[0], y = edge[1]; adj[x].add(y); adj[y].add(x); } boolean[] visited = new boolean[n]; return dfs(source, destination, adj, visited); } public boolean dfs(int source, int destination, List<Integer>[] adj, boolean[] visited) { if (source == destination) { return true; } visited[source] = true; for (int next : adj[source]) { if (!visited[next] && dfs(next, destination, adj, visited)) { return true; } } return false; } } 作者:力扣官方题解 链接:https://leetcode.cn/problems/find-if-path-exists-in-graph/solutions/2024085/xun-zhao-tu-zhong-shi-fou-cun-zai-lu-jin-d0q0/ 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值