여기서 방문하지 않은 곳이 즉 새로 탐색하는 곳이면 (영역이 다르면 그 구간에서 ++)
하고 실제 dfs 이구간에서는 같은 부분 만 탐색하도록 범위 체크를 먼저 하고 그 다름 탐색을 해야한다.
import java.io.*;
import java.util.*;
import java.util.*;
public class Main{
static int n;
static char 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 IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
map=new char[n][n];
visited=new boolean[n][n];
for(int i=0;i<n;i++){
String line=br.readLine();
for(int j=0;j<n;j++){
map[i][j]=line.charAt(j);
}
}
int Normalcnt=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(!visited[i][j]){
dfs(i,j);
Normalcnt++;
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(map[i][j]=='R'){
map[i][j]='G';
}
}
}
visited=new boolean[n][n];
int RGcnt=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(!visited[i][j]){
dfs(i,j);
RGcnt++;
}
}
}
System.out.println(Normalcnt+" "+RGcnt);
}
public static void dfs(int H,int W){
visited[H][W]=true;
for(int i=0;i<4;i++){
int Ry=H+dy[i];
int Rx=W+dx[i];
if(Ry>=0 && Ry<n && Rx>=0 && Rx<n){
if(!visited[Ry][Rx] && map[H][W]==map[Ry][Rx]){
dfs(Ry,Rx);
}
}
}
}
}'프로그래머스 백준 문제' 카테고리의 다른 글
| 프로그래머스 HashMap 기본문제 (0) | 2026.07.22 |
|---|---|
| 코테 Scanner 객체 사용법 (0) | 2026.07.21 |
| 가장 긴 공통인 수열(문장) (0) | 2025.07.16 |
| 12015 번 가장 긴 증가하는 부분 수열2 (0) | 2025.07.16 |
| 3986 좋은 단어 (0) | 2025.07.14 |