뚱땅뚱땅

[문제] 백준 10026번 적록색약 본문

알고리즘/백준

[문제] 백준 10026번 적록색약

양순이 2021. 3. 3. 21:32
728x90

* 출처

www.acmicpc.net/problem/10026

 

10026번: 적록색약

적록색약은 빨간색과 초록색의 차이를 거의 느끼지 못한다. 따라서, 적록색약인 사람이 보는 그림은 아닌 사람이 보는 그림과는 좀 다를 수 있다. 크기가 N×N인 그리드의 각 칸에 R(빨강), G(초록)

www.acmicpc.net

문제 풀이

 

dfs로 풀면 된다.

public class Main {
	static int N;
	static char[][] matrix;
	static boolean[][] visited;
	
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		N = Integer.parseInt(in.readLine());

		matrix = new char[N][N];
		visited = new boolean[N][N];

		for (int i = 0; i < N; i++) {
			String s = in.readLine();
			for (int j = 0; j < N; j++) {
				matrix[i][j] = s.charAt(j);
			}
		}
		int total = 0;
		for(int i=0;i<N;i++) {
			for(int j=0;j<N;j++) {
				if(!visited[i][j]) {
					dfs(i,j);
					total++;
				}
			}
		}
		System.out.print(total+ " ");
		total = 0;
		visited = new boolean[N][N];
		for(int i=0;i<N;i++) {
			for(int j=0;j<N;j++) {
				if(matrix[i][j] == 'G') matrix[i][j]= 'R';
			}
		}
		for(int i=0;i<N;i++) {
			for(int j=0;j<N;j++) {
				if(!visited[i][j]) {
					dfs(i,j);
					total++;
				}
			}
		}
		System.out.println(total);
	}

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

	static void dfs(int x, int y) {
		visited[x][y] = true;

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

			if (nx >= 0 && nx < N && ny >= 0 && ny < N && !visited[nx][ny]) {
				if (matrix[x][y] == matrix[nx][ny]) {
					
					dfs(nx, ny);
				} 
			}
		}
	}
}
728x90
Comments