https://www.acmicpc.net/problem/10026
: R,G,B 구역 개수 프린트 && RG,B 구역 개수 프린트
import java.util.*;
public class Main {
static int N;
static int ColorCount = 0;
static int[][] map ;
static boolean[][] visited;
static int[] dx = {-1,0,1,0};
static int[] dy = {0,1,0,-1};
public static void main(String[] args) throws Exception{
// 값 입력받기 -- >
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
map = new int[N][N];
visited = new boolean[N][N];
for(int i=0; i<N; i++) {
String str = sc.next();
for(int j=0; j<N; j++) {
map[i][j] = str.charAt(j);
}
}
// <-- 값 입력받기
//R,G,B 영역 개수 구하기 -->
DFS();
System.out.println(ColorCount);
//<--
// R,B 영역 개수를 구하기 위한 초기화 및 값 변경
ColorCount = 0;
visited = new boolean[N][N];
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if(map[i][j] == 'R') map[i][j] = 'G';
}
}
// R,B 영역 개수 구하기 -->
DFS();
System.out.println(ColorCount);
<--
}
public static void DFS(){
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if(!visited[i][j]){
FindZone(i,j,map[i][j]);
ColorCount += 1;
}
}
}
}
public static void FindZone(int x, int y,int nowColor){
visited[x][y] = true;
for(int i=0;i<4;i++){
int xx = x+dx[i];
int yy = y+dy[i];
if (xx<0 || xx>=N || yy<0 || yy>=N) continue;
if (map[xx][yy]==nowColor && !visited[xx][yy]){
FindZone(xx,yy,nowColor);
}
}
}
}
DFS()
: 0,0 ~ N,N 까지 반복 중 (i,j)가 방문X 일 때 FindZone(i,j,map[i][j]) 실행
FindZone(int x, int y, int nowColor)
: x,y 방문O
: (x,y) 상하좌우의 값 탐색, nowColor 랑 같으면 FindColor(x좌표,y좌표,nowColor)