백준

백준 10026 적록색약(Java)

Park DJ 2023. 2. 25. 14:33

https://www.acmicpc.net/problem/10026

 

10026번: 적록색약

적록색약은 빨간색과 초록색의 차이를 거의 느끼지 못한다. 따라서, 적록색약인 사람이 보는 그림은 아닌 사람이 보는 그림과는 좀 다를 수 있다. 크기가 N×N인 그리드의 각 칸에 R(빨강), G(초록)

www.acmicpc.net


 

Java 코드

 


import java.util.Scanner;

public class Main {

  static int n;
  static int[] dx = {1, -1, 0, 0};
  static int[] dy = {0, 0, -1, 1};
  static char[][] arr;
  static boolean[][] visit;
  static StringBuilder sb = new StringBuilder();

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int count1 = 0;
    int count2 = 0;
    n = sc.nextInt();
    arr = new char[n][n];
    visit = new boolean[n][n];
    
    for(int i = 0; i < n; i++) {
      String str = sc.next();
      for(int j = 0; j < n; j++) {
        arr[i][j] = str.charAt(j);
      }
    }

    for(int i = 0; i < n; i++) {
      for(int j = 0; j < n; j++) {
        if(visit[i][j] == false) {
          count1++;
          dfs(i, j);
        }
      }
    }

    sb.append(count1+" ");
    visit = new boolean[n][n];

     for(int i = 0; i < n; i++) {
      for(int j = 0; j < n; j++) {
        if(arr[i][j] == 'G') arr[i][j] = 'R';
      }
    }

    for(int i = 0; i < n; i++) {
      for(int j = 0; j < n; j++) {
        if(visit[i][j] == false) {
          count2++;
          dfs(i, j);
        }
      }
    }

    sb.append(count2);

    System.out.println(sb);
  }

  public static void dfs(int a, int b) {
    visit[a][b] = true;
    for(int i = 0; i < 4; i++) {
      int x = a + dx[i];
      int y = b + dy[i];
      if(x >= 0 && x < n && y >= 0 && y < n && visit[x][y] == false && arr[x][y] == arr[a][b]) dfs(x, y);
    }
  }
}