https://www.acmicpc.net/problem/10026
10026번: 적록색약
적록색약은 빨간색과 초록색의 차이를 거의 느끼지 못한다. 따라서, 적록색약인 사람이 보는 그림은 아닌 사람이 보는 그림과는 좀 다를 수 있다. 크기가 N×N인 그리드의 각 칸에 R(빨강), G(초록)
www.acmicpc.net
파라미터를 한 개 더 추가해 줘서 푼 문제이다.
미로 찾기에서 딱히 다른 건 없는 거 같다.
import java.io.*;
import java.util.*;
public class Main {
static char map[][] = new char[101][101];
static boolean visited[][] = new boolean[101][101];
static int dx[] = {-1, 0, 1, 0};
static int dy[] = {0, 1, 0, -1};
static int n;
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(bf.readLine());
for (int i = 0; i < n; i++) {
String mapStr = bf.readLine();
for (int j = 0; j < mapStr.length(); j++) {
map[i][j] = mapStr.charAt(j);
}
}
int cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (visited[i][j] == false) {
bfs(i, j, map[i][j]);
cnt++;
}
}
}
System.out.print(cnt + " ");
cnt = 0;
initMap();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (visited[i][j] == false) {
bfsRGB(i, j, map[i][j]);
cnt++;
}
}
}
System.out.print(cnt);
}
static class pair {
int x;
int y;
pair(int x, int y) {
this.x = x;
this.y = y;
}
}
static void bfs(int _x, int _y, char rgb) {
Queue<pair> q = new LinkedList<>();
q.add(new pair(_x, _y));
while (!q.isEmpty()) {
int x = q.peek().x;
int y = q.peek().y;
q.poll();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || nx > n - 1 || ny < 0 || ny > n - 1)
continue;
if (map[nx][ny] == rgb && visited[nx][ny] == false) {
visited[nx][ny] = true;
q.add(new pair(nx, ny));
}
}
}
}
static void bfsRGB(int _x, int _y, char rgb) {
Queue<pair> q = new LinkedList<>();
q.add(new pair(_x, _y));
while (!q.isEmpty()) {
int x = q.peek().x;
int y = q.peek().y;
q.poll();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || nx > n - 1 || ny < 0 || ny > n - 1)
continue;
if (rgb == 'R' || rgb == 'G') {
if ((map[nx][ny] == 'R' || map[nx][ny] == 'G') && visited[nx][ny] == false) {
visited[nx][ny] = true;
q.add(new pair(nx, ny));
}
} else {
if (map[nx][ny] == rgb && visited[nx][ny] == false) {
visited[nx][ny] = true;
q.add(new pair(nx, ny));
}
}
}
}
}
static void print() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(visited[i][j] + " ");
}
System.out.println();
}
}
static void initMap() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
visited[i][j] = false;
}
}
}
}
'알고리즘' 카테고리의 다른 글
[백준] 17413번 : 단어 뒤집기 2 (0) | 2023.03.03 |
---|---|
[백준] 14490번 : 백대열 (1) | 2023.02.27 |
[백준] 4949번 : 균형잡힌 세상 (0) | 2023.02.25 |
[백준] 4963번 : 섬의 개수 (0) | 2023.02.24 |
[백준] 14502번 : 연구소 (0) | 2023.02.23 |