Number of Connected Components in an Undirected Graph
Posted keepshuatishuati
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Number of Connected Components in an Undirected Graph相关的知识,希望对你有一定的参考价值。
1 public class Solution { 2 private int[] parent; 3 public int countComponents(int n, int[][] edges) { 4 if (edges.length == 0) { 5 return n; 6 } 7 parent = new int[n]; 8 for (int i = 0; i < n; i++) { 9 parent[i] = i; 10 } 11 12 for (int i = 0; i < edges.length; i++) { 13 int aIndex = findParent(edges[i][0]); 14 int bIndex = findParent(edges[i][1]); 15 16 if (aIndex > bIndex) { 17 parent[aIndex] = bIndex; 18 } else if (bIndex > aIndex) { 19 parent[bIndex] = aIndex; 20 } 21 } 22 23 int result = 0; 24 for (int i = 0; i < n; i++) { 25 if (parent[i] == i) { 26 result++; 27 } 28 } 29 return result; 30 } 31 32 private int findParent(int x) { 33 while (x != parent[x]) { 34 parent[x] = parent[parent[x]]; 35 x = parent[x]; 36 } 37 return x; 38 } 39 }
以上是关于Number of Connected Components in an Undirected Graph的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 323. Number of Connected Components in an Undirected Graph 无向图中的连通区域的个数
[LeetCode] 694. Number of Distinct Islands
694. Number of Distinct Islands - Medium
[LC] 694. Number of Distinct Islands