[백준] P10026

동민·2021년 3월 11일
import java.util.Scanner;

public class P10026 { // Flood Fill 알고리즘	

	static int n;
	static boolean[][] visit;
	static char[][] picture;
	static int[] dx = { 0, 0, -1, 1 }; // 상하좌우
	static int[] dy = { 1, -1, 0, 0 }; // 상하좌우

	public static void main(String[] args) { 
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		picture = new char[n][n];

		for (int i = 0; i < n; i++) {
			char[] str = sc.next().toCharArray();
			for (int j = 0; j < n; j++) {
				picture[i][j] = str[j];
			}
		}

		System.out.print(solution(picture) + " ");
		make_R_equal_G(picture);
		System.out.println(solution(picture));

		sc.close();
	}

	private static int solution(char[][] picture) { // 영역을 계산하는 함수
		int cnt = 0;
		visit = new boolean[n][n];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (!visit[i][j]) {
					cnt++;
					dfs(i, j, picture[i][j]);
				}
			}
		}
		return cnt;
	}

	private static void dfs(int x, int y, char color) {

		if (visit[x][y]) { // StackOverFlow 방지
			return;
		}
		visit[x][y] = true;

		for (int i = 0; i < 4; i++) { // 상하좌우 DFS 탐색
			int newX = x + dx[i];
			int newY = y + dy[i];
			if (isValid(newX, newY) && color == picture[newX][newY]) {
				dfs(newX, newY, color);
			}
		}
	}

	private static void make_R_equal_G(char[][] picture) { // 적록색약 -> G를 R로 치환
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				picture[i][j] = picture[i][j] == 'G' ? 'R' : picture[i][j];
			}
		}
	}

	private static boolean isValid(int x, int y) { // 0 ~ N-1 안으로 들어오는지 확인
		return (x < 0 || x >= n || y < 0 || y >= n) ? false : true;
	}
}
profile
BE Developer

0개의 댓글