관리 메뉴

기억을 위한 기록들

[백준 3184: 양] - C++ 본문

Coding Test - cpp/BFS

[백준 3184: 양] - C++

에드윈H 2021. 3. 4. 17:04

www.acmicpc.net/problem/3184

 

3184번: 양

첫 줄에는 두 정수 R과 C가 주어지며(3 ≤ R, C ≤ 250), 각 수는 마당의 행과 열의 수를 의미한다. 다음 R개의 줄은 C개의 글자를 가진다. 이들은 마당의 구조(울타리, 양, 늑대의 위치)를 의미한다.

www.acmicpc.net

#include <iostream>
#include <queue>
#include <string>
using namespace std;

char map[251][251];
int visited[251][251];
int dir[4][2] = {
{-1,0}
,{0,1}
,{1,0}
,{0,-1}
};
int r, c;
int vCnt = 0;
int oCnt = 0;
void bfs(int _x, int _y)
{
	queue < pair<int, int>> q;
	visited[_x][_y] = 1;

	q.push({ _x,_y });
	while (!q.empty())
	{
		int curX = q.front().first;
		int curY = q.front().second;
		q.pop();
		for (int i = 0; i < 4; i++)
		{
			int nextX = curX + dir[i][0];
			int nextY = curY + dir[i][1];

			if (nextY < 0 || nextX < 0 || r <= nextX || c <= nextY)
				continue;
			if (!visited[nextX][nextY] && (map[nextX][nextY] == '.' || map[nextX][nextY] == 'o' || map[nextX][nextY] == 'v'))
			{
				visited[nextX][nextY] = 1;
				q.push({ nextX,nextY });
				if (map[nextX][nextY] == 'o')
					oCnt++;
				else if (map[nextX][nextY] == 'v')
					vCnt++;
			}
		}
	}
}
int main(void)
{
	cin >> r >> c;
	string n;
	for (int i = 0; i < r; i++)
	{
		cin >> n;
		for (int j = 0; j < c; j++)
		{
			map[i][j] = n[j];
		}
	}


	bool bcheck = false;

	int vCntTotal = 0;
	int oCntTotal = 0;
	for (int i = 0; i < r; i++)
	{
		for (int j = 0; j < c; j++)
		{
			bcheck = false;
			if (map[i][j] == 'v' && !visited[i][j])
			{
				vCnt = 1;
				oCnt = 0;
				bfs(i, j);
				bcheck = true;
			}
			else if (map[i][j] == 'o' && !visited[i][j])
			{
				vCnt = 0;
				oCnt = 1;
				bfs(i, j);
				bcheck = true;
			}


			if (bcheck)
			{
				if (vCnt >= oCnt)
				{
					vCntTotal += vCnt;
				}
				else {
					oCntTotal += oCnt;
				}
			}
			
		}
	}

	cout << oCntTotal << " " << vCntTotal << '\n';
	return 0;

}