diff options
author | Haidong Ji | 2020-05-16 21:22:14 -0500 |
---|---|---|
committer | Haidong Ji | 2020-05-16 21:22:14 -0500 |
commit | 2dd66619bbd1bf45e092c54f70d89d8f27d269dc (patch) | |
tree | 78d9eef9e53f9389b299012e3b92eb0f2625012e /src/main | |
parent | bc5a6815181068e76316aa4a611647124d18ba48 (diff) |
ConnectedComponents (Adding Exits to Maze) done. I didn't build my test cases properly initially: when v and w are connected, they should be in each other's ArrayList. Once that's fixed, it was easy.
Diffstat (limited to 'src/main')
-rw-r--r-- | src/main/ConnectedComponents.java | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/src/main/ConnectedComponents.java b/src/main/ConnectedComponents.java new file mode 100644 index 0000000..915509c --- /dev/null +++ b/src/main/ConnectedComponents.java @@ -0,0 +1,44 @@ +import java.util.ArrayList; +import java.util.Scanner; + +public class ConnectedComponents { + + static int numberOfComponents(ArrayList<ArrayList<Integer>> adj) { + ArrayList<Integer> visited = new ArrayList<>(); + int cc = 0; + for (int v = 0; v < adj.size(); v++) { + if (!visited.contains(v)) { + explore(adj, visited, v); + cc++; + } + } + return cc; + } + + private static void explore(ArrayList<ArrayList<Integer>> adj, ArrayList<Integer> visited, int v) { + visited.add(v); + + for (int n : adj.get(v)) { + if (!visited.contains(n)) + explore(adj, visited, n); + } + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + int n = scanner.nextInt(); + int m = scanner.nextInt(); + ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); + for (int i = 0; i < n; i++) { + adj.add(new ArrayList<Integer>()); + } + for (int i = 0; i < m; i++) { + int x, y; + x = scanner.nextInt(); + y = scanner.nextInt(); + adj.get(x - 1).add(y - 1); + adj.get(y - 1).add(x - 1); + } + System.out.println(numberOfComponents(adj)); + } +} |