Advertisement
Guest User

graph

a guest
Aug 18th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.ArrayList;
  3. /**
  4.  *
  5.  * @author henrico
  6.  * problem 459
  7.  */
  8. public class Main {
  9.     private static ArrayList<Integer>[] graph;
  10.     private static boolean[] visited;
  11.     private static int count;
  12.    
  13.     public static void main(String[] args) {
  14.         Scanner sc = new Scanner(System.in);
  15.         int n = sc.nextInt();
  16.         sc.nextLine();
  17.         for(int i = 0;i<n;i++){
  18.             int max = sc.next().charAt(0) - 'A' +1 ;
  19.             graph = new ArrayList[max];
  20.             visited = new boolean[max];
  21.             for(int j = 0; j<max;j++){
  22.                 graph[j] = new ArrayList<Integer>();
  23.             }
  24.             sc.nextLine();
  25.             String tmp = sc.nextLine();
  26.             while(!tmp.equals("")){
  27.                 int x = tmp.charAt(0)-'A';
  28.                 int y = tmp.charAt(1)-'A';
  29.                 graph[x].add(y);
  30.                 graph[y].add(x);
  31.                 tmp = sc.nextLine();
  32.             }
  33.             count = 0;
  34.             for(int j=0;j<max;j++){
  35.                 if(!visited[j]){
  36.                     count++;
  37.                     dfs(j);
  38.                 }
  39.             }
  40.             System.out.println(count);
  41.             System.out.println();
  42.         }
  43.     }
  44.    
  45.     private static void dfs(int idx){
  46.         visited[idx]=true;
  47.         for(int i = 0; i<graph[idx].size();i++){
  48.             if(!visited[graph[idx].get(i)]){
  49.                 dfs(graph[idx].get(i));
  50.             }
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement