[Java] 10026 적록색약

ideal dev·2022년 12월 18일
0

코딩테스트

목록 보기
15/69

1. 문제 링크 및 문제

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

1-1 문제 요약

: R,G,B 구역 개수 프린트 && RG,B 구역 개수 프린트

2. 해결 방법 생각해보자 ...

  1. 전체맵에서 R,G,B 의 영역 개수를 DFS() 로 구함.
  2. 전체맵에서 R 을 G 로 (또는 G를 R로) 바꿔줌.
  3. 다시 전체맵을 DFS() 돌림.

3. 코드

import java.util.*;

public class Main {

    static int N;
    static int ColorCount = 0;
    static int[][] map ;
    static boolean[][] visited;

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

    public static void main(String[] args) throws Exception{

        // 값 입력받기 -- >
        Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		map = new int[N][N];
		visited = new boolean[N][N];

		for(int i=0; i<N; i++) {
            String str = sc.next();
			for(int j=0; j<N; j++) {
				map[i][j] = str.charAt(j);
			}
		}
        // <-- 값 입력받기
        
        //R,G,B 영역 개수 구하기 -->
        DFS();
        System.out.println(ColorCount);
        //<--
        
        // R,B 영역 개수를 구하기 위한 초기화 및 값 변경
        ColorCount = 0;
        visited = new boolean[N][N];
        for(int i=0;i<N;i++){
            for(int j=0;j<N;j++){
                if(map[i][j] == 'R') map[i][j] = 'G';
            }
        }

		// R,B 영역 개수 구하기 -->
        DFS();
        System.out.println(ColorCount);
        <--

    }

    public static void DFS(){
        for(int i=0;i<N;i++){
            for(int j=0;j<N;j++){
                if(!visited[i][j]){
                    FindZone(i,j,map[i][j]);
                    ColorCount += 1;
                }
            }
        }
    }

    public static void FindZone(int x, int y,int nowColor){
        visited[x][y] = true;
        for(int i=0;i<4;i++){
            int xx = x+dx[i];
            int yy = y+dy[i];
            if (xx<0 || xx>=N || yy<0 || yy>=N) continue;
            if (map[xx][yy]==nowColor && !visited[xx][yy]){
                FindZone(xx,yy,nowColor);
            }
        }

    }

}

DFS()
: 0,0 ~ N,N 까지 반복 중 (i,j)가 방문X 일 때 FindZone(i,j,map[i][j]) 실행

FindZone(int x, int y, int nowColor)
: x,y 방문O
: (x,y) 상하좌우의 값 탐색, nowColor 랑 같으면 FindColor(x좌표,y좌표,nowColor)

0개의 댓글