Created
August 27, 2020 18:23
-
-
Save bvolpato/ad62f036460c8a065657490771e77dfb to your computer and use it in GitHub Desktop.
DFS - Number of Clusters
This file contains 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
import java.util.Scanner; | |
/** | |
* DFS Number of Groups Java Implementation | |
*/ | |
public class Clusters { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
int n = sc.nextInt(); | |
for (int T = 0; T < n; T++) { | |
int c = sc.nextInt(); | |
boolean[][] D = new boolean[c][c]; | |
boolean[] visited = new boolean[c]; | |
int clusters = 0; | |
int left = c; | |
int r = sc.nextInt(); | |
for (int k = 0; k < r; k++) { | |
int c1 = sc.nextInt(); | |
int c2 = sc.nextInt(); | |
D[c1][c2] = true; | |
D[c2][c1] = true; | |
} | |
for (int i = 0; i < visited.length; i++) { | |
if (!visited[i]) { | |
dfs(D, visited, i); | |
clusters++; | |
} | |
} | |
System.out.println(clusters); | |
} | |
} | |
private static void dfs(boolean[][] d, boolean[] visited, int node) { | |
for (int j = 0; j < d.length; j++) { | |
if (d[node][j] && !visited[j]) { | |
visited[j] = true; | |
dfs(d, visited, j); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment