백준 10026번 적록색약

최성현·2021년 2월 14일
0

백준 문제풀이

목록 보기
18/29

문제 링크

😎 코드 설명

처음에는 어렵게 생각했지만 일반적인 DFS 방법으로 풀린다.

문제에선 R,G,B의 알파벳으로 나왔지만 dfs내에서 기존 x,y 와 그다음 nx,ny가 같을때 넣어주고 visit배열을 채워주면된다.

main에서 시작점을 넣어주는것도 visit배열에 방문하지만 않으면 전부 넣어주면된다.

😎 소스 코드

#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
int n;
char map[101][101];
bool visit[101][101];
int dy[] = { 0,0,-1,1 };
int dx[] = { 1,-1,0,0 };
int cnt = 0;
void dfs(int y, int x) {
	visit[y][x] = true;
	for (int i = 0; i < 4; i++) {
		int ny = y + dy[i];
		int nx = x + dx[i];

		if (ny < 0 || ny >= n || nx < 0 || nx >= n) continue;
		if (map[ny][nx] == map[y][x] && !visit[ny][nx]) {
			
			dfs(ny, nx);
		}
	}

}
int main() {
		
	cin >> n;
	for (int y = 0; y < n; y++) {
		for (int x = 0; x < n; x++) {
			cin >> map[y][x];

		}
	}

	for (int y = 0; y < n; y++) {
		for (int x = 0; x < n; x++) {
			
			if (!visit[y][x]) {
				cnt++;
				dfs(y, x);


			}
			
		}
	}
	memset(visit, false, sizeof(visit)); //visit다시 초기화
	int cnt2 = 0;
	for (int y = 0; y < n; y++) {
		for (int x = 0; x < n; x++) {
			if (map[y][x] == 'R')
				map[y][x] = 'G';
		}
	}
	for (int y = 0; y < n; y++) {
		for (int x = 0; x < n; x++) {
			if (!visit[y][x]) {
				cnt2++;
				dfs(y, x);
			}
		}
	}


	cout << cnt << " " << cnt2;
	return 0;
}
profile
후회없이

0개의 댓글