문제


일단 생각하기!
- 적록색약이 아닌 사람과 적록색약인 사람이 보는 그림은 다르기 때문에 두 개의 배열을 만들어 적록색약인 사람의 배열에서는
R을 G로 바꿔주었다. (난 초록을 좋아하기 때문에 ㅋㅋ)
- 아무튼! 방문한 칸인지 체크하기 위해
boolean 타입 배열을 만들어 가장 최근 값과 사방탐색을 하여 이동한 값이 같은지 비교해준다. 이때, for문을 돌릴때 방문되었는지 먼저 체크해주고 함수를 호출해줘야 한다. 또한, 사방탐색 하여 이동한 값도 방문되었는지 체크해주어야 한다.
- 처음엔 BFS와 DFS가 마냥 어렵기만 했는데 이해가 되니 재밌기도 하다. 마스터 할때까지 파이팅 😤
풀이
package BJ;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BJ_10026_적록색약_김유나 {
static int n, cnt = 0;
static boolean isVisited[][];
static int[][] deltas = { { -1, 0 }, { 1, 0 }, { 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());
char [][] arr = new char[n][n];
char [][] colorArr = new char[n][n];
isVisited = new boolean[n][n];
for (int i = 0; i < n; i++) {
String str = br.readLine();
for (int j = 0; j < n; j++) {
char c = str.charAt(j);
arr[i][j] = c;
if (c == 'R') colorArr[i][j] = 'G';
else colorArr[i][j] = c;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (!isVisited[i][j]) {
dfs(i, j, arr);
cnt++;
}
}
}
System.out.print(cnt);
isVisited = new boolean[n][n];
cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (!isVisited[i][j]) {
dfs(i, j, colorArr);
cnt++;
}
}
}
System.out.println(" " + cnt);
}
static void dfs(int x, int y, char arr[][]) {
isVisited[x][y] = true;
char current = arr[x][y];
for (int i = 0; i < 4; i++) {
int dx = x + deltas[i][0];
int dy = y + deltas[i][1];
if (dx < 0 || dy < 0 || dx >= n || dy >= n)
continue;
if (!isVisited[dx][dy] && arr[dx][dy] == current) {
dfs(dx, dy, arr);
}
}
}
}