带权平均
把根节点挂在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/