Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- class Main {
- public static void main(String args[]) throws IOException {
- BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
- int N = Integer.parseInt(read.readLine());
- ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
- for(int i=0; i<N; i++)
- {
- String S[] = read.readLine().split(" ");
- ArrayList<Integer> temp = new ArrayList<>();
- for(int j=0; j<N; j++)
- temp.add(Integer.parseInt(S[j]));
- adj.add(temp);
- }
- Solution ob = new Solution();
- System.out.println(ob.components(adj,N));
- }
- }
- class Solution {
- void dfs(ArrayList<ArrayList<Integer>> M, int[] visited, int i)
- {
- for (int j = 0; j < M.size(); j++)
- {
- if (i!=j && M.get(i).get(j) == 1 && visited[j] == 0)
- {
- visited[j] = 1;
- dfs(M, visited, j);
- }
- }
- }
- int components(ArrayList<ArrayList<Integer>> adj, int N) {
- int[] visited = new int[adj.size()];
- int count = 0;
- for (int i = 0; i < adj.size(); i++)
- {
- if (visited[i] == 0)
- {
- dfs(adj, visited, i);
- count++;
- }
- }
- return count;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement