https://www.acmicpc.net/problem/10026
Main
static int N;
static char [][] arr;
static boolean visits[][];
static int dx[] = {-1,0,0,1};
static int dy[] = {0,1,-1,0};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N =Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
StringTokenizer st ;
visits = new boolean[N+1][N+1];
arr = new char[N+1][N+1];
for (int i = 0; i <N ; i++) {
st = new StringTokenizer(br.readLine());
String Value = st.nextToken();
for (int j = 0; j <N ; j++) {
arr[i][j] = Value.charAt(j);
}
}
//정상일때
int Ncnt =0;
for (int i = 0; i <N ; i++) {
for (int j = 0; j <N ; j++) {
if(!visits[i][j]){
dfs(i,j);
Ncnt++;
}
}
}
visits = new boolean[N+1][N+1];
//적록색약일때
int abCnt=0;
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(!visits[i][j]){
dfs(i,j);
abCnt++;
}
}
}
sb.append(Ncnt).append(" ").append(abCnt);
System.out.println(sb.toString());
}
dfs
public static void dfs(int x, int y){
visits[x][y] = true;
char colorChar = arr[x][y];
for (int k = 0; k <4 ; k++) {
int newX = x+dx[k];
int newY = y+dy[k];
if(newX < 0||newY < 0 || newX > N ||newY >N){
continue;
}
if(!visits[newX][newY] && arr[newX][newY]== colorChar){
dfs(newX,newY);
}
}
}
- dfs, bfs 중 어떤거 써서풀지
- 상하좌우를 어떻게 방문하고, 방문했을때와 안했을때 구분을 어떻게 할지