정답 코드
import java.util.*;
public class Main {
static int N;
static char[][] grid;
static boolean[][] visitedNormal, visitedColorBlind;
static int[] dx = {0, 0, -1, 1};
static int[] dy = {-1, 1, 0, 0};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
grid = new char[N][N];
visitedNormal = new boolean[N][N];
visitedColorBlind = new boolean[N][N];
for (int i = 0; i < N; i++) {
grid[i] = sc.next().toCharArray();
}
int normalCount = 0;
int colorBlindCount = 0;
// 적록색약이 아닌 경우
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (!visitedNormal[i][j]) {
dfs(i, j, grid[i][j], false);
normalCount++;
}
if (!visitedColorBlind[i][j]) {
dfs(i, j, grid[i][j], true);
colorBlindCount++;
}
}
}
System.out.println(normalCount + " " + colorBlindCount);
}
// DFS 탐색
static void dfs(int x, int y, char color, boolean isColorBlind) {
if (isColorBlind) visitedColorBlind[x][y] = true;
else visitedNormal[x][y] = true;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || ny < 0 || nx >= N || ny >= N) continue;
if (isColorBlind && !visitedColorBlind[nx][ny] && isSameColor(color, grid[nx][ny], true)) {
dfs(nx, ny, color, true);
} else if (!isColorBlind && !visitedNormal[nx][ny] && isSameColor(color, grid[nx][ny], false)) {
dfs(nx, ny, color, false);
}
}
}
// 색상 비교 (적록색약 여부에 따라 다름)
static boolean isSameColor(char color1, char color2, boolean isColorBlind) {
if (isColorBlind) {
if (color1 == 'R' || color1 == 'G') return color2 == 'R' || color2 == 'G';
}
return color1 == color2;
}
}
코드 설명
1. 입력 처리
N과 그림 데이터를 입력받습니다.
각각의 visitedNormal과 visitedColorBlind 배열로 적록색약 여부에 따라 방문 여부를 관리합니다.
2. DFS 탐색
시작점에서 인접한 칸들을 재귀적으로 탐색하며 같은 구역으로 판단합니다.
적록색약의 경우 R과 G를 동일한 색으로 간주합니다.
3. 구역 개수 계산
방문하지 않은 시작점을 기준으로 DFS를 호출하여 구역 개수를 증가시킵니다.
4. 색상 비교 로직
isSameColor 함수로 적록색약 여부에 따른 색상 비교를 수행합니다
'코딩 테스트 일지 📒' 카테고리의 다른 글
[백준] 16953 A → B | DFS, BFS, 그래프 | 실버 Ⅱ | JAVA (0) | 2024.11.27 |
---|---|
[백준] 11725 트리의 부모 찾기 | DFS, BFS, 그래프 | 실버 Ⅱ | JAVA (0) | 2024.11.25 |
[백준] 11724 연결 요소의 개수 | DFS, BFS, 그래프 | 실버 Ⅱ | JAVA (0) | 2024.11.24 |
[백준] 2667 단지번호붙이기 | DFS, BFS, 그래프 | 실버 Ⅰ | JAVA (0) | 2024.11.22 |
[백준] 2606 바이러스 | DFS, BFS, 그래프 | 실버 Ⅲ | JAVA (0) | 2024.11.21 |