Computer Science/Algorithm Problem

백준] 10026 - 적록색약(USACO March 2014 Bronze)

TwinParadox 2019. 3. 31. 11:02
728x90

시간 제한 : 1초
메모리 제한 : 128MB

 

 


입력
첫째 줄에 N이 주어진다. (1 ≤ N ≤ 100)
둘째 줄부터 N개 줄에는 그림이 주어진다.

 

 


출력
적록색약이 아닌 사람이 봤을 때의 구역의 개수와 적록색약인 사람이 봤을 때의 구역의 수를 공백으로 구분해 출력한다.

 

 


소스코드

#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
int N;
int dir[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
vector<string> arr;
vector<vector<bool> > check;
bool isValid(int coord)
{
	return coord >= 0 && coord < N;
}
void BFS(int i, int j, int RGB)
{
	queue<pair<int, int> > q;
	q.push(make_pair(i, j));
	check[i][j] = true;
	while (!q.empty())
	{
		int cx = q.front().first, cy = q.front().second;
		q.pop();
		for (int i = 0; i < 4; i++)
		{
			int nx = cx + dir[i][0], ny = cy + dir[i][1];
			if (isValid(nx) && isValid(ny) && !check[nx][ny])
			{
				if (RGB == 0 && (arr[nx][ny] == 'R' || arr[nx][ny] == 'G'))
				{
					check[nx][ny] = true;
					q.push(make_pair(nx, ny));
				}
				if (RGB == 1 && arr[nx][ny] == 'R')
				{
					check[nx][ny] = true;
					q.push(make_pair(nx, ny));
				}
				else if (RGB == 2 && arr[nx][ny] == 'G')
				{
					check[nx][ny] = true;
					q.push(make_pair(nx, ny));
				}
				else if (RGB == 3 && arr[nx][ny] == 'B')
				{
					check[nx][ny] = true;
					q.push(make_pair(nx, ny));
				}
			}
		}
	}
}
int main(void)
{
	int ans1 = 0, ans2 = 0;
	cin >> N;
	arr = vector<string>(N);
	check = vector<vector<bool> >(N, vector<bool>(N, false));
	for (int i = 0; i < N; i++)
		cin >> arr[i];

	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			if (!check[i][j])
			{
				ans1++;
				if (arr[i][j] == 'R')
					BFS(i, j, 1);
				else if (arr[i][j] == 'G')
					BFS(i, j, 2);
				else
					BFS(i, j, 3);
			}
		}
	}

	check = vector<vector<bool> >(N, vector<bool>(N, false));
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			if (!check[i][j])
			{
				ans2++;
				if (arr[i][j] == 'R' || arr[i][j] == 'G')
					BFS(i, j, 0);
				else if (arr[i][j] == 'B')
					BFS(i, j, 3);
			}
		}
	}

	cout << ans1 << ' ' << ans2;
}

 

 


Tip

이 문제 크게 어려운 건 없었다. 중~하 난이도의 BFS, DFS 문제이기 때문에 어렵지 않게 풀 수 있다. 다만, 적록 색약인 경우와 아닌 경우에 따라 어떻게 탐색을 진행할지 고민을 잠깐 했다. 그냥 적록색약인 경우와 아닌 경우에 따른 플래그 값을 주고 풀었다.

 

728x90
728x90