본문 바로가기

CodingTEST

[백준 10026] 적록색약 (JAVA)

반응형

백준 10026번 문제 - 적록색약

 

10026번: 적록색약

적록색약은 빨간색과 초록색의 차이를 거의 느끼지 못한다. 따라서, 적록색약인 사람이 보는 그림은 아닌 사람이 보는 그림과는 좀 다를 수 있다. 크기가 N×N인 그리드의 각 칸에 R(빨강), G(초록)

www.acmicpc.net


문제 분석 

 

  • 적록색약이 아닌 사람이 봤을 때 구역의 수와 적록색약(빨간 초록 구분 못함)이 봤을 때 구역 수를 출력해라.

 

해결 포인트

 

  • BFS 구현
  • 적록색약일 경우 색을 저장하는 이차원배열과, 적록색약일 경우 색을 저장하는 이차원배열을 따로 구현
    • 적록색약일 경우 색을 저장하는 이차원 배열은 빨간색하고 초록색 모두 초록색으로 저장한다.

 


 

코드

 

import java.awt.*;
import java.io.*;
import java.util.*;

public class Main {
    public static boolean [][] visit;
    public static int N;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        N = Integer.parseInt(br.readLine());
        char [][] colors = new char [N][N];
        char [][] nonColors = new char [N][N];
        for (int i = 0; i < N; i++) {
            String s = br.readLine();
            for (int j = 0; j < N; j++) {
                colors[i][j] = s.charAt(j);
                if(colors[i][j] == 'R')
                    nonColors[i][j] = 'G';
                else
                    nonColors[i][j] = colors[i][j];
            }
        }

        visit = new boolean[N][N];
        int colorCount = 0;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (!visit[i][j]) {
                    colorCount++;
                    colorBFS(new Point(i, j), colors, colors[i][j]);
                }
            }
        }

        visit = new boolean[N][N];
        int nonColorCount = 0;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (!visit[i][j]) {
                    nonColorCount++;
                    colorBFS(new Point(i, j), nonColors, nonColors[i][j]);
                }
            }
        }

        bw.write(colorCount + " " + nonColorCount);

        bw.flush();
        bw.close();
    }

    public static void colorBFS(Point p, char [][] colors, char color) {
        Queue<Point> queue = new LinkedList<>();
        int [] dx = {0,0,1,-1};
        int [] dy = {1,-1,0,0};

//        char color = colors[p.x][p.y];
        visit[p.x][p.y] = true;
        queue.add(p);

        while (!queue.isEmpty()) {
            Point newP = queue.poll();

            for (int i = 0; i < 4; i++) {
                int nextX = newP.x + dx[i];
                int nextY = newP.y + dy[i];

                if(checkRound(nextX, nextY) && color==colors[nextX][nextY] && !visit[nextX][nextY]) {
                    visit[nextX][nextY] = true;
                    queue.add(new Point(nextX, nextY));
                }
            }
        }
    }

    public static boolean checkRound(int x, int y) {
        return x >= 0 && y>=0 && x < N && y < N;
    }
}
반응형