728x90
문제
R, G, B 세 가지 색상으로 이루어진 그림이 주어졌을 때
적록색약인 사람과 아닌 사람이 볼 수 있는 구역의 수를 구하라
접근 방식
적녹색약인 사람은 R과 G를 같은 색깔로 볼 것이기 때문에
둘을 하나의 색으로 취급해서 BFS를 돌면서
출발지가 몇 개인지 카운트하면 되고
색약이 아닌 사람은 세 가지 색상 모두 출발지를 카운트하면 된다.
풀고 나니 반복문의 사용이 쓸데없이 많은거 같아
반복문을 좀 더 효율적으로 돌 수 있는 방법을 생각해봐야겠다.
풀이
public class Main {
private static final int[] dx = {1, 0, -1, 0};
private static final int[] dy = {0, 1, 0, -1};
private static final char[] rgbColor = {'R', 'G', 'B'};
private static final char[] gbColor = {'G', 'B'};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
char[][] rgbGrid = new char[n][n];
char[][] gbGrid = new char[n][n];
boolean[][] rgbIsVisited = new boolean[n][n];
boolean[][] gbIsVisited = new boolean[n][n];
int rgb = 0;
int gb = 0;
Queue<Pair> rgbQueue = new ArrayDeque<>();
Queue<Pair> gbQueue = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
char[] input = br.readLine().toCharArray();
for (int j = 0; j < n; j++) {
rgbGrid[i][j] = input[j];
if (input[j] == 'R') {
gbGrid[i][j] = 'G';
} else {
gbGrid[i][j] = input[j];
}
}
}
for (char c : rgbColor){
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (rgbIsVisited[i][j] || rgbGrid[i][j] != c)
continue;
rgb++;
rgbQueue.offer(new Pair(i, j));
rgbIsVisited[i][j] = true;
while (!rgbQueue.isEmpty()) {
Pair cur = rgbQueue.poll();
for (int dir = 0; dir < 4; dir++) {
int nx = cur.x + dx[dir];
int ny = cur.y + dy[dir];
if (nx < 0 || nx >= n || ny < 0 || ny >= n)
continue;
if (rgbIsVisited[nx][ny] || rgbGrid[nx][ny] != c)
continue;
rgbQueue.offer(new Pair(nx, ny));
rgbIsVisited[nx][ny] = true;
}
}
}
}
}
for (char c : gbColor){
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (gbIsVisited[i][j] || gbGrid[i][j] != c)
continue;
gb++;
gbQueue.offer(new Pair(i, j));
gbIsVisited[i][j] = true;
while (!gbQueue.isEmpty()) {
Pair cur = gbQueue.poll();
for (int dir = 0; dir < 4; dir++) {
int nx = cur.x + dx[dir];
int ny = cur.y + dy[dir];
if (nx < 0 || nx >= n || ny < 0 || ny >= n)
continue;
if (gbIsVisited[nx][ny] || gbGrid[nx][ny] != c)
continue;
gbQueue.offer(new Pair(nx, ny));
gbIsVisited[nx][ny] = true;
}
}
}
}
}
System.out.println(rgb + " " + gb);
}
private static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
}
'Java > Algorithms' 카테고리의 다른 글
[백준] 1629번 : 곱셈 (1) | 2023.10.13 |
---|---|
[백준] 11728번 : 배열 합치기 (0) | 2023.10.12 |
[백준] 1012번 : 유기농 배추 (0) | 2023.10.11 |
[백준] 1697번 : 숨바꼭질 (0) | 2023.10.11 |
[백준] 4179번 : 불! (0) | 2023.10.10 |