🐣 알고리즘 삐약/💻 백준 삐약

63 삐약 : 백준 10026| 적록색약 [바킹독 문제 풀이|BFS|JAVA]

우주수첩 2024. 6. 3. 22:29
728x90

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

 

package BKD_0x9_BFS;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

public class BOJ_10026 {
    static char[][] RGB_colors;
    static char[][] RG_B_colors;
    static int[] dx ={0,1,0,-1};
    static int[] dy ={1,0,-1,0};
    static int N;
    public static void main(String[] args) throws IOException {
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        String input;
        int rgb_cnt=0;
        int rg_b_cnt=0;

        RGB_colors = new char[N][N];
        RG_B_colors = new char[N][N];

        for(int i=0;i<N;i++){
            input = br.readLine();
            for(int j=0;j<N;j++){
                char temp = input.charAt(j);
                RGB_colors[i][j] = temp;

                if(temp=='G')temp ='R';
                RG_B_colors[i][j]=temp;
            }
        }
        for(int i=0;i<N;i++){
            for(int j=0;j<N;j++){
                if(RGB_colors[i][j]!='X'){
                    RGB(true,i,j);
                    rgb_cnt++;
                }if(RG_B_colors[i][j]!='X'){
                    RGB(false,i,j);
                    rg_b_cnt++;
                }
            }
        }
        System.out.printf("%d %d",rgb_cnt,rg_b_cnt);
    }

    static void RGB(boolean key,int x , int y){
        Queue<Pair> q = new LinkedList<>();
        char[][] temp = (key) ? RGB_colors : RG_B_colors;
        char rgb = temp[x][y];
        q.offer(new Pair(x,y));

        while(!q.isEmpty()){
            Pair p = q.poll();
            temp[p.x][p.y]='X';

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

                if(nx>=0 && ny>=0 && nx<N&& ny<N){
                    if(temp[nx][ny]==rgb && temp[nx][ny]!='X') {
                        temp[nx][ny]='X';
                        q.offer(new Pair(nx,ny));
                    }
                }
            }
        }



    }

    static class Pair{
        int x;
        int y;

        public Pair(int x, int y){
            this.x = x;
            this.y = y;
        }
    }

}

 

적록색맹인 경우와 아닌경우의 입력을 다르게 하여 풀이를 진행하였다.

bfs메소드 하나로 탐색을 진행하기 위해서 자바 얕은 복사를 통해 상황에 필요한 배열을 복사하여 진행하였다.

 

728x90