문제풀이/백준
[백준]10026: 적록색약 - JAVA
빈둥벤둥
2021. 2. 14. 18:03
[백준]10026: 적록색약

10026번: 적록색약
적록색약은 빨간색과 초록색의 차이를 거의 느끼지 못한다. 따라서, 적록색약인 사람이 보는 그림은 아닌 사람이 보는 그림과는 좀 다를 수 있다. 크기가 N×N인 그리드의 각 칸에 R(빨강), G(초록)
www.acmicpc.net
풀이
탐색 문제로 dfs, bfs로 둘다 풀어도 될 듯하다. 적록색약이 아닌 사람이 봤을 때의 구역의 수는 일반적인 dfs와 똑같고, 적록색약인 사람의 구역의 수를 구할 때는 R, G인 값을 같다고 생각하고 체크해주었다.
이정도는 이제 어렵지 않다!
코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
import java.util.*;
public class Main {
static int[] dx = {0, -1, 0, 1};
static int[] dy = {1, 0, -1, 0};
static int n;
static char board[][];
static boolean normalvisited[][], redgreenvisited[][];
static int normalCount = 0, redgreenCount = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
scan.nextLine();
board = new char[n][n];
for(int i = 0; i < n; i++) {
String str = scan.nextLine();
for(int j = 0; j < n; j++) {
board[i][j] = str.charAt(j);
}
}
normalvisited = new boolean[n][n];
redgreenvisited = new boolean[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(normalvisited[i][j] == false) {
dfs(i, j);
normalCount++;
}
if(redgreenvisited[i][j] == false) {
redgreendfs(i, j);
redgreenCount++;
}
}
}
System.out.print(normalCount + " " + redgreenCount);
}
public static void dfs(int x, int y) {
normalvisited[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) {
if(normalvisited[nx][ny] == false && board[nx][ny] == board[x][y]) {
normalvisited[nx][ny] = true;
dfs(nx, ny);
}
}
}
}
public static void redgreendfs(int x, int y) {
redgreenvisited[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) {
if(redgreenvisited[nx][ny] == false) {
if((board[x][y] == 'R' || board[x][y] == 'G') && (board[nx][ny] == 'R' || board[nx][ny] == 'G')) {
redgreenvisited[nx][ny] = true;
redgreendfs(nx, ny);
}
else if(board[x][y] == board[nx][ny]) {
redgreenvisited[nx][ny] = true;
redgreendfs(nx, ny);
}
}
}
}
}
}
|
cs |