https://www.acmicpc.net/problem/10026
1. 현재 위치와 같은 문자가 나오는 경우 계속 DFS 로 방문하게 되는 함수 DFS
2. R과 G가 같은 문자로 인식되므로 flag 변수를 따로 생성하여 R 혹은 G인경우 flag 변수를 true 값으로 설정하여
분류하였다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int RGB = 0, RGB2 = 0;
static int N;
static boolean flag;
static char map[][];
static boolean visited[][];
static int[] dy = {1, 0, -1, 0};
static int[] dx = {0, 1, 0, -1};
public static void main(String[] agrs) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
map = new char[N + 1][N + 1];
visited = new boolean[N + 1][N + 1];
for (int i = 1; i <= N; i++) {
String tmp = br.readLine();
for (int j = 1; j <= tmp.length(); j++) {
map[i][j] = tmp.charAt(j - 1);
}
}
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
// 방문한 적이 없으면
if (!visited[i][j]) {
DFS(i, j);
RGB++;
}
}
}
visited = new boolean[N + 1][N + 1];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
// 방문한 적이 없으면
if (!visited[i][j]) {
DFS2(i, j);
RGB2++;
}
}
}
System.out.println(RGB+" "+ RGB2);
}
static void DFS(int y, int x) {
visited[y][x] = true;
char cur = map[y][x];
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ny < 0 || nx < 0 || N < ny || N < nx)
continue;
if (!visited[ny][nx] && map[ny][nx] == cur)
DFS(ny, nx);
}
}
static void DFS2(int y, int x) {
visited[y][x] = true;
char cur = map[y][x];
// R 혹은 G 인경우는 flag = true
if (cur == 'R' || cur == 'G')
flag = true;
else
flag = false;
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ny < 0 || nx < 0 || N < ny || N < nx)
continue;
if (visited[ny][nx])
continue;
// flag 가 true 인경우는 R,G 인경우 이므로
if (flag && (map[ny][nx] == 'R' || map[ny][nx] == 'G')){
DFS2(ny, nx);
}
else if (!flag && map[ny][nx] == 'B'){
DFS2(ny, nx);
}
}
}
}
'프로그래밍 & IT > Algorithm' 카테고리의 다른 글
[알고리즘] 프로그래머스 위장 :: 우유 (0) | 2022.10.03 |
---|---|
[알고리즘] 프로그래머스 구명보트 :: 우유 (0) | 2022.10.03 |
[알고리즘] 백준 4963번 섬의개수 :: 우유 (0) | 2022.06.19 |
[알고리즘] 백준 11047번 동전 0 :: 우유 (0) | 2022.06.09 |
[알고리즘] 백준 4949번 균형잡힌세상 :: 우유 (0) | 2022.06.09 |