백준 3184 c++

magicdrill·2024년 2월 21일

백준 문제풀이

목록 보기
6/673

백준 3184 c++

BFS를 통해 푸는 문제이다.
각 덩어리에서 양과 늑대의 마릿수를 저장하고 덩어리 내에서의 BFS가 종료되면 남은 마릿수를 따로 저장해야 한다.

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

int R, C;
vector <vector<char>> graph(250, vector <char>(250, 0));
vector <vector<bool>> visited(250, vector <bool>(250, false));

void input_graph()
{
	int i, j;

	for (i = 0; i < R; i++)
	{
		for (j = 0; j < C; j++)
		{
			cin >> graph[i][j];
		}
	}
	/*for (i = 0; i < R; i++)
	{
		for (j = 0; j < C; j++)
		{
			cout << graph[i][j] << " ";
		}
		cout << "\n";
	}*/

	return;
}

void BFS(int start_y, int start_x, int *sheep, int *wolf)
{
	int current_x, current_y, next_x, next_y;
	int i, j;
	vector<pair<int, int>> direction = { {1, 0},{0, 1},{-1, 0},{0, -1} };
	queue<pair<int, int>> q;
	int v = 0, o = 0;

	q.push({ start_x, start_y });
	visited[start_y][start_x] = true;
	if (graph[start_y][start_x] == 'v')
	{
		v++;
	}
	else if (graph[start_y][start_x] == 'o')
	{
		o++;
	}
	else
	{
		;
	}
	while (!q.empty())
	{
		current_x = q.front().first;
		current_y = q.front().second;
		q.pop();
		for (i = 0; i < 4; i++)
		{
			next_x = current_x + direction[i].first;
			next_y = current_y + direction[i].second;
			if ((next_x >= 0 && next_x < C) && (next_y >= 0 && next_y < R) && visited[next_y][next_x] == false)
			{
				if (graph[next_y][next_x] == '#')
				{
					;
				}
				else if(graph[next_y][next_x] == 'v')//늑대
				{
					visited[next_y][next_x] = true;
					q.push({ next_x, next_y });
					v++;
				}
				else if (graph[next_y][next_x] == 'o')//양
				{
					visited[next_y][next_x] = true;
					q.push({ next_x, next_y });
					o++;
				}
				else//graph[][] == '.'
				{
					visited[next_y][next_x] = true;
					q.push({ next_x, next_y });
				}
			}
		}
	}
	//cout << "v : " << v << " / o : " << o << "\n";
	if (o > v)
	{
		*sheep += o;
		*wolf += 0;
	}
	else
	{
		*sheep += 0;
		*wolf += v;
	}

	return;
}

void find_answer()
{
	int i, j;
	int sheep = 0, wolf = 0;

	for (i = 0; i < R; i++)
	{
		for (j = 0; j < C; j++)
		{
			if (visited[i][j] == false && graph[i][j] != '#')
			{
				BFS(i, j, &sheep, &wolf);
			}
		}
	}
	cout << sheep << " " << wolf << "\n";

	return;
}

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	cin >> R >> C;
	input_graph();
	find_answer();

	return 0;
}

0개의 댓글