[백준] #10026 - 적록색약

짱수·2023년 4월 14일
0

알고리즘 문제풀이

목록 보기
15/26

🔒문제 설명

적록색약은 빨간색과 초록색의 차이를 거의 느끼지 못한다. 따라서, 적록색약인 사람이 보는 그림은 아닌 사람이 보는 그림과는 좀 다를 수 있다.

크기가 N×N인 그리드의 각 칸에 R(빨강), G(초록), B(파랑) 중 하나를 색칠한 그림이 있다. 그림은 몇 개의 구역으로 나뉘어져 있는데, 구역은 같은 색으로 이루어져 있다. 또, 같은 색상이 상하좌우로 인접해 있는 경우에 두 글자는 같은 구역에 속한다. (색상의 차이를 거의 느끼지 못하는 경우도 같은 색상이라 한다)

예를 들어, 그림이 아래와 같은 경우에

RRRBB
GGBBB
BBBRR
BBRRR
RRRRR

적록색약이 아닌 사람이 봤을 때 구역의 수는 총 4개이다. (빨강 2, 파랑 1, 초록 1) 하지만, 적록색약인 사람은 구역을 3개 볼 수 있다. (빨강-초록 2, 파랑 1)

그림이 입력으로 주어졌을 때, 적록색약인 사람이 봤을 때와 아닌 사람이 봤을 때 구역의 수를 구하는 프로그램을 작성하시오.

입력


첫째 줄에 N이 주어진다. (1 ≤ N ≤ 100)

둘째 줄부터 N개 줄에는 그림이 주어진다.

출력


적록색약이 아닌 사람이 봤을 때의 구역의 개수와 적록색약인 사람이 봤을 때의 구역의 수를 공백으로 구분해 출력한다.

🔑해결 아이디어

이번 문제는 그림에서 구역의 개수를 찾는 탐색 문제였다. 일반적인 BFS 문제처럼 풀면 된다.
객체지향으로 풀면서 가장 핵심이 되었던 부분은 Color 클래스의 equals() 메서드였다.
어떤 사람이 보는지에 따라 같은 구역으로 처리할 수도, 다른 구역으로 처리할 수도 있었다.
그래서 equals() 메서드에 Person 객체를 넘겨주고, Person의 상태에 따라 equals() 메서드의 결과를 다르게 구현하는 방법을 택하였다.

💻소스코드

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class BJ10026 {
    //10:30 ~ 11:30
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int lineNum = sc.nextInt();
        sc.nextLine();
        Paint paint = new Paint(lineNum);

        for(int l = 0; l<lineNum; l++){
            String line = sc.nextLine();
            char[] colors = line.toCharArray();
            paint.grid[l] = new Color[colors.length];

            for (int i = 0; i<colors.length; i++) {
                paint.grid[l][i] = new Color(l, i, colors[i]);
            }
        }

        Person person = new Person(false, paint);
        Person RgPerson = new Person(true, paint);


        person.search();
        RgPerson.search();

        System.out.println(person.areaNum + " " + RgPerson.areaNum);


    }
}
class Paint{
   Color[][] grid;

   Paint(int n){
       grid = new Color[n][];
   }
}

class Area{
    Queue<Color> search;

    Area(Color color){
        search = new LinkedList<>();
        search.add(color);
    }

    void search(Person person, Paint paint){
        while (search.isEmpty() == false) {
            Color currentColor = search.poll();
            //System.out.println("\npoll : "+ currentColor.toString());
            Color newColor;

            if(currentColor.row > 0){
                newColor = paint.grid[currentColor.row - 1][currentColor.col];
                checkNewColor(person, currentColor, newColor);
            }

            if(currentColor.row < paint.grid.length-1){
                newColor = paint.grid[currentColor.row +1][currentColor.col];
                checkNewColor(person, currentColor, newColor);
            }

            if(currentColor.col > 0){
                newColor = paint.grid[currentColor.row][currentColor.col -1];
                checkNewColor(person, currentColor, newColor);
            }

            if(currentColor.col < paint.grid[0].length-1){
                newColor = paint.grid[currentColor.row][currentColor.col +1];
                checkNewColor(person, currentColor, newColor);
            }
        }
    }

    private void checkNewColor(Person person, Color currentColor, Color newColor) {
        //System.out.println("Check : " + newColor.toString());
        if (person.notUsed.contains(newColor) == false) {
            return;
        }
        if (currentColor.equals(newColor, person)) {
            person.notUsed.remove(newColor);
            search.add(newColor);
            //System.out.println("add Color : "+ newColor.toString());
        }
    }
}
class Color{
    int row;
    int col;
    char color;

    Color(int row, int col, char color) {
        this.row = row;
        this.col = col;
        this.color = color;
    }

    public String toString(){
        return this.row + " " + this.col + " " + this.color;
    }
    boolean equals(Color anotherColor, Person person) {
        if(person.RG){
            if(this.color == 'B'){
                return this.color == anotherColor.color;
            }
            else{
                if(anotherColor.color == 'B')
                    return false;
                else
                    return true;
            }
        }

        else
            return this.color == anotherColor.color;
    }
}
class Person {
    HashSet<Color> notUsed;
    Paint paint;
    boolean RG;
    int areaNum;

    Person(boolean rg, Paint paint){
        notUsed = new HashSet<>();
        this.paint = paint;
        areaNum = 0;
        this.RG = rg;

        for (int i = 0; i< paint.grid.length; i++) {
            for (int j = 0; j < paint.grid[0].length;j++) {
                notUsed.add(paint.grid[i][j]);
            }
        }
    }

    void search(){
        while(!notUsed.isEmpty()){
            areaNum++;
            Color notUsedColor = (Color)notUsed.toArray()[0];
            notUsed.remove(notUsedColor);
            Area area = new Area(notUsedColor);
            area.search(this, paint);
        }
    }
}

⭐️ 반성

2차원 이상의 배열을 탐색할 때는 rowcol, 또는 xy 등의 각 좌표를 헷갈리지 않도록 조심해야 한다.

profile
Zangsu

0개의 댓글