• Home
  • About
    • Ryureka Moment photo

      Ryureka

      Sin Prisa, Sin Pausa

    • About Me
    • Facebook
    • Github
    • Youtube
  • Projects
  • Posts
    • Posts
    • ProblemSolvings
    • Tags
    • Blog
    • Examples
  • ProblemSolving
    • ProblemSolving
    • BOJ
    • Programmers
    • SWEA
    • LeetCode
  • FrontEnd
    • FrontEnd
    • HTML
  • BackEnd
    • BackEnd
    • Server
      • Server
      • Spring
      • NodeJS
    • DataBase
      • DataBase
      • MySQL
      • MongoDB
  • Programming
    • Programming
    • Java
    • JS
    • Python
    • CleanCode
  • ComputerScience
    • DataStructure
    • Algorithm

[BOJ] 10026. 적록색약

15 Apr 2026

Reading time ~1 minute

  • 풀이

풀이

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

public class Main {
	static Scanner sc=new Scanner(System.in);
	static int N=sc.nextInt();
	static char map[][]=new char[N][N];
	static boolean discovered[][]=new boolean[N][N];
	
	static int dx[]= {1,0,-1,0};
	static int dy[]= {0,1,0,-1};
	public static void main(String[] args) {
		sc.nextLine();
		for (int i = 0; i < N; i++) {
			String s=sc.nextLine();
			for (int j = 0; j < N; j++) {
				map[i][j]=s.charAt(j);
			}
		}
        
		int cnt1=0;
		for (int i = 0; i < map.length; i++) {
			for (int j = 0; j < map.length; j++) {
				if(!discovered[i][j]) {
					bfs(i,j,map[i][j],false);
					cnt1++;
				}
			}
		}
		
		for (int i = 0; i < map.length; i++) {
			for (int j = 0; j < map.length; j++) {
				discovered[i][j]=false;
			}
		}
		
		int cnt2=0;
		for (int i = 0; i < map.length; i++) {
			for (int j = 0; j < map.length; j++) {
				if(!discovered[i][j]) {
					bfs(i,j,map[i][j],true);
					cnt2++;
				}
			}
		}
		
		System.out.println(cnt1+" "+cnt2);
	}
	
	
	public static void bfs(int x,int y,char ch,boolean flag) {
		Queue<Point> q=new LinkedList<>();
		q.add(new Point(x,y));
		discovered[x][y]=true;
		while(!q.isEmpty()) {
			Point c=q.poll();
			int nx,ny;
			for (int i = 0; i < 4; i++) {
				nx=c.x+dx[i];
				ny=c.y+dy[i];
				if(nx<0 || ny<0 || nx>N-1 || ny>N-1) continue;
				if(!flag) {
					if(map[nx][ny]==ch && !discovered[nx][ny]) {
						discovered[nx][ny]=true;
						q.add(new Point(nx,ny));
					}
				}else {
					if(ch=='R'||ch=='G') {
						if((map[nx][ny]=='R' || map[nx][ny]=='G')&& !discovered[nx][ny]) {
							discovered[nx][ny]=true;
							q.add(new Point(nx,ny));
						}
					}else {
						if(map[nx][ny]==ch && !discovered[nx][ny]) {
							discovered[nx][ny]=true;
							q.add(new Point(nx,ny));
						}
					}
				}
			}
		}
	}
	
	public static class Point{
		int x,y;
		Point(int x,int y){
			this.x=x;
			this.y=y;
		}
	}
}


BFS Share