Created
November 18, 2018 19:41
-
-
Save wszdwp/46c9a34446a62dc3c2f7b4dc489a1fc0 to your computer and use it in GitHub Desktop.
check connected components in dynamic graph
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 2 union find, better for checking connected components in dymanic graph | |
| public int findCircleNum(int[][] M) { | |
| int[] id = new int[M.length]; | |
| for (int i = 0; i < id.length; i++) id[i] = i; | |
| int[] count = new int[1]; | |
| count[0] = id.length; | |
| for (int i = 0; i < M.length; i++) { | |
| for (int j = i; j < M[0].length; j++) { | |
| if (M[i][j] == 1 && i != j) union(i, j, count, id); | |
| } | |
| } | |
| return count[0]; | |
| } | |
| private void union(int i, int j, int[] count, int[] id) { | |
| int iRoot = root(i, id); | |
| int jRoot = root(j, id); | |
| if (iRoot == jRoot) return; | |
| id[iRoot] = jRoot; | |
| count[0]--; | |
| } | |
| private int root(int i, int[] id) { | |
| while (i != id[i]) i = id[i]; | |
| return i; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment