[알고리즘] 백준 > #10026. 적록색약

Chloe Choi·2020년 12월 6일
0

Algorithm

목록 보기
5/71

주말 끝 ㅜ,ㅜ

문제링크

백준 #10026. 적록색약

풀이방법

쉬운 문제였다. 보면 바로 dfs나 bfs로 풀 수 있는 문제인걸 알 수 있다. dfs를 이용해 구역을 탐색했다. 적록색약이 아닌 사람 / 적록색약인 사람 각각 비교를 다르게 해 문제를 해결했다.

// 적록색약이 아닌 사람
(a, b) -> a == b
// 적록색약인 사람
(a, b) -> (a == b) || ((a != 'B') && (b != 'B'))

코드

import java.util.Scanner;

public class RedGreenColorBlindness {
    static int n;
    static char[][] painting;
    static boolean[][] visitied;

    static int[] dy = {0, 0, +1, -1};
    static int[] dx = {+1, -1, 0, 0};

    static SectionCheckerService checkerService = new SectionCheckerService();

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        n = Integer.parseInt(sc.nextLine());
        painting = new char[n][n];
        visitied = new boolean[n][n];
        for (int i = 0; i < n; i++) {
            String input = sc.nextLine();
            for (int j = 0; j < n; j++) {
                painting[i][j] = input.charAt(j);
            }
        }

        StringBuilder result = new StringBuilder();

        // 적록색약이 아닌 사람이 봤을 때 구역 수 구하기
        int numOfSection = getNumOfSection((a, b) -> a == b);
        result.append(numOfSection);
        result.append(" ");

        // 적록색약인 사람이 봤을 때 구역 수 구하기
        numOfSection = getNumOfSection((a, b) -> (a == b) || ((a != 'B') && (b != 'B')));
        result.append(numOfSection);

       System.out.print(result.toString());
    }

    private static int getNumOfSection(SectionChecker checker) {
        int numOfSection = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) visitied[i][j] = false;
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (!visitied[i][j]) {
                    searchSection(i, j, checker);
                    numOfSection++;
                }
            }
        }

        return numOfSection;
    }

    private static void searchSection(int y, int x, SectionChecker checker) {
        visitied[y][x] = true;

        for (int i = 0; i < 4; i++) {
            int moveY = y + dy[i];
            int moveX = x + dx[i];

            if (isInRange(moveY, moveX) && !visitied[moveY][moveX] && checkerService.isSameSection(checker, painting[y][x], painting[moveY][moveX])) {
                searchSection(moveY, moveX, checker);
            }
        }
    }

    private static boolean isInRange(int y, int x) {
        if ((y >= 0) && (y < n) && (x >= 0) && (x < n)) return true;
        else return false;
    }
}

interface SectionChecker {
    boolean isSameSection(char a, char b);
}

class SectionCheckerService {
    boolean isSameSection(SectionChecker checker, char a, char b) {return checker.isSameSection(a, b);}
}
profile
똑딱똑딱

0개의 댓글