Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Created November 18, 2018 19:40
Show Gist options
  • Select an option

  • Save wszdwp/8a530291d5c936d7fb71edcd6e70c7d4 to your computer and use it in GitHub Desktop.

Select an option

Save wszdwp/8a530291d5c936d7fb71edcd6e70c7d4 to your computer and use it in GitHub Desktop.
checking connected components in graph
// 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