문제 풀이 및 개발 공간

[백준] 10026번 적록색약 (gold 5 본문

백준공부/java

[백준] 10026번 적록색약 (gold 5

gomduri43 2023. 12. 21. 20:46

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

class Point{
    int x;
    int y;
    char stat;
    public Point(int x, int y, char stat){
        this.x=x;
        this.y=y;
        this.stat=stat;
    }
}
public class Main{
    static int[] numx={-1,1,0,0};
    static int[] numy={0,0,-1,1};
    public static void main(String[] args) throws IOException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
        int n=Integer.valueOf(br.readLine());
        char[][] map=new char[n+1][n+1];
        for(int i=1; i<=n; i++){
            String a=br.readLine();
            for(int j=1; j<=n; j++){
                map[i][j]=a.charAt(j-1);
            }
        }

        Queue<Point> que=new LinkedList<>();
        boolean[][] visit=new boolean[n+1][n+1];
        int answer1=0;
        for(int i=1; i<=n; i++){
            for(int j=1; j<=n; j++){
                if(!visit[i][j]){
                    answer1++;
                    visit[i][j]=true;
                    que.offer(new Point(j,i,map[i][j]));
                    while(!que.isEmpty()){
                        Point temp=que.poll();
                        for(int k=0; k<4; k++){
                            int tpx=temp.x+numx[k];
                            int tpy=temp.y+numy[k];
                            if(tpx<1 || tpx>n || tpy<1 || tpy>n || visit[tpy][tpx] || temp.stat != map[tpy][tpx]){
                                continue;
                            }
                            visit[tpy][tpx]=true;
                            que.offer(new Point(tpx,tpy, temp.stat));
                        }
                    }
                }
            }
        }
        que.clear();
        visit=new boolean[n+1][n+1];
        int answer2=0;
        for(int i=1; i<=n; i++){
            for(int j=1; j<=n; j++){
                if(!visit[i][j]){
                    answer2++;
                    visit[i][j]=true;
                    que.offer(new Point(j,i,map[i][j]));
                    while(!que.isEmpty()){
                        Point temp=que.poll();
                        for(int k=0; k<4; k++){
                            int tpx=temp.x+numx[k];
                            int tpy=temp.y+numy[k];
                            if(tpx<1 || tpx>n || tpy<1 || tpy>n || visit[tpy][tpx] || (temp.stat=='B' || map[tpy][tpx]=='B') && (temp.stat != map[tpy][tpx])){
                                continue;
                            }
                            visit[tpy][tpx]=true;
                            que.offer(new Point(tpx,tpy, map[tpy][tpx]));
                        }
                    }
                }
            }
        }
        bw.write(answer1+" "+answer2);
        bw.flush();
    }
}