BOJ_G5_10026
π [G5_10026] μ λ‘μμ½
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int[] dx = {0,0,1,-1};
static int[] dy = {1,-1,0,0,};
static char[][] arr;
static int N;
static boolean[][] v;
static int cnt;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
// ν¬κΈ°
N = Integer.parseInt(br.readLine());
// μ
λ ₯
arr = new char[N+1][N+1];
v = new boolean[N+1][N+1];
for (int i = 0; i < N; i++) {
String str = br.readLine();
for (int j = 0; j < N; j++) {
arr[i][j] = str.charAt(j);
}
}
// κΈ°λ³Έ
cnt = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if(!v[i][j]){
dfs(i,j);
cnt++;
}
}
}
sb.append(cnt).append(" ");
// μλ§Ή
cnt = 0;
v = new boolean[N+1][N+1];
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(!v[i][j]){
dfs(i,j);
cnt++;
}
}
}
sb.append(cnt);
System.out.println(sb);
}
static void dfs(int x, int y) {
v[x][y] = true;
char num = arr[x][y];
for (int z = 0; z < 4; z++) {
int nx = x + dx[z];
int ny = y + dy[z];
if (nx < 0 || ny < 0 || nx > N || ny > N) {
continue;
}
else if (!v[nx][ny] && arr[nx][ny] == num) {
dfs(nx, ny);
}
}
}
}
π€ λμ μκ°
dfsμ λ°©ν₯νμμ ν©νμ¬ κ΅¬ννμλ€.
λ¨Όμ μ λ‘μμ½μ΄ μλ μ¬λμ΄ λ΄€μ λμ ꡬμμ κ°μλ μ²μ μμΉ λΆν° 4λ°©ν₯ νμμ νλ©° dfs() μκ³ λ¦¬μ¦μ μννλ©΄ ꡬμλ€μ΄ λμ¨λ€.
κ·Έ ꡬμμ μΉ΄μ΄ν
ν΄μ£Όκ³ μ 체 μΉ΄μ΄ν
μ ꡬν΄μ£Όλ©΄ λλ€.
λ€μ μ λ‘μμ½μ΄ μλ μ¬λμ΄ λ΄€μ λλ Gλ₯Ό Rλ‘ λ°κΏμ£Όκ³ λκ°μ λ°©μμΌλ‘ ꡬννλ©΄ λλ€.
dfsμ λ°©ν₯νμμ ꡬνν μ€ μλ€λ©΄ μ΄λ ΅μ§ μμ λ¬Έμ μλ€.