Created
November 18, 2018 19:40
-
-
Save wszdwp/8a530291d5c936d7fb71edcd6e70c7d4 to your computer and use it in GitHub Desktop.
checking connected components in 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
| // Lt547 friend circle | |
| // 1 dfs, better for checking connected components in static graph | |
| public int findCircleNum(int[][] M) { | |
| if (M.length == 0 || M[0].length == 0) return 0; | |
| int m = M.length; | |
| int n = M[0].length; | |
| boolean[] visited = new boolean[m]; | |
| int ans = 0; | |
| for (int i = 0; i < m; i++) { | |
| if (!visited[i]) { | |
| dfs(M, i, visited); | |
| ++ans; | |
| } | |
| } | |
| return ans; | |
| } | |
| private void dfs(int[][] M, int curr, boolean[] visited) { | |
| if (visited[curr]) return; | |
| visited[curr] = true; | |
| for (int i = 0; i < M[curr].length; i++) { | |
| if (!visited[i] && M[curr][i] == 1) { | |
| dfs(M, i, visited); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment