https://www.acmicpc.net/problem/10026

 

10026번: 적록색약

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

www.acmicpc.net


1. 현재 위치와 같은 문자가 나오는 경우 계속 DFS 로 방문하게 되는 함수 DFS
2. R과 G가 같은 문자로 인식되므로 flag 변수를 따로 생성하여 R 혹은 G인경우 flag 변수를 true 값으로 설정하여
분류하였다.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    static int RGB = 0, RGB2 = 0;
    static int N;
    static boolean flag;
    static char map[][];
    static boolean visited[][];
    static int[] dy = {1, 0, -1, 0};
    static int[] dx = {0, 1, 0, -1};

    public static void main(String[] agrs) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        N = Integer.parseInt(br.readLine());

        map = new char[N + 1][N + 1];
        visited = new boolean[N + 1][N + 1];

        for (int i = 1; i <= N; i++) {
            String tmp = br.readLine();
            for (int j = 1; j <= tmp.length(); j++) {
                map[i][j] = tmp.charAt(j - 1);
            }
        }

        for (int i = 1; i <= N; i++) {
            for (int j = 1; j <= N; j++) {
                // 방문한 적이 없으면
                if (!visited[i][j]) {
                    DFS(i, j);
                    RGB++;
                }
            }
        }
        visited = new boolean[N + 1][N + 1];

        for (int i = 1; i <= N; i++) {
            for (int j = 1; j <= N; j++) {
                // 방문한 적이 없으면
                if (!visited[i][j]) {
                    DFS2(i, j);
                    RGB2++;
                }
            }
        }

        System.out.println(RGB+" "+ RGB2);
    }

    static void DFS(int y, int x) {
        visited[y][x] = true;

        char cur = map[y][x];

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

            if (ny < 0 || nx < 0 || N < ny || N < nx)
                continue;

            if (!visited[ny][nx] && map[ny][nx] == cur)
                DFS(ny, nx);
        }
    }

    static void DFS2(int y, int x) {
        visited[y][x] = true;

        char cur = map[y][x];

        // R 혹은 G 인경우는 flag = true
        if (cur == 'R' || cur == 'G')
            flag = true;
        else
            flag = false;


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

            if (ny < 0 || nx < 0 || N < ny || N < nx)
                continue;

            if (visited[ny][nx])
                continue;
            
            // flag 가 true 인경우는 R,G 인경우 이므로
            if (flag && (map[ny][nx] == 'R' || map[ny][nx] == 'G')){
                DFS2(ny, nx);
            }
            else if (!flag && map[ny][nx] == 'B'){
                DFS2(ny, nx);
            }
        }
    }
}

+ Recent posts