백준 3187 c++

magicdrill·2024년 4월 11일

백준 문제풀이

목록 보기
291/675

백준 3187 c++

간단한 BFS문제이다. DFS로도 풀어볼 수 있을 거 같다.
전역변수를 최대한 안 만들어 보려고 해봤다.

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

using namespace std;

vector <vector<char>> graph;
vector <vector<bool>> visited;

void input_graph(int *R, int *C)
{
	int i, j;

	cin >> *R >> *C;
	graph.resize(*R, vector<char>(*C, ' '));
	visited.resize(*R, vector<bool>(*C, false));
	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 DFS(int start_x, int start_y, int *wolf, int *sheep, int R, int C)
{
	int v = 0, k = 0;
	int current_x, current_y, next_x, next_y;
	queue<pair<int, int>> q;
	vector<pair<int, int>> direction{ {1, 0},{0, 1},{-1, 0},{0, -1} };
	int d_size = direction.size();
	int i;

	if (graph[start_y][start_x] == 'k')
	{
		k++;
	}
	else
	{
		v++;
	}
	q.push({ start_x, start_y });
	visited[start_y][start_x] = true;
	while (!q.empty())
	{
		current_x = q.front().first;
		current_y = q.front().second;
		q.pop();
		for (i = 0; i < d_size; 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)
				&& (graph[next_y][next_x] != '#'))
			{
				if (graph[next_y][next_x] == 'k')
				{
					q.push({next_x, next_y});
					visited[next_y][next_x] = true;
					k++;
				}
				else if (graph[next_y][next_x] == 'v')
				{
					q.push({ next_x, next_y });
					visited[next_y][next_x] = true;
					v++;
				}
				else
				{
					q.push({ next_x, next_y });
					visited[next_y][next_x] = true;
				}
			}
		}
	}
	//cout << "k : " << k << " v : " << v << "\n";
	if (k > v)
	{
		*sheep += k;
		*wolf += 0;
	}
	else//v >= k
	{
		*sheep += 0;
		*wolf += v;
	}

	return;
}

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

	for (i = 0; i < R; i++)
	{
		for (j = 0; j < C; j++)
		{
			if ((graph[i][j] == 'v' || graph[i][j] == 'k') && visited[i][j] == false)
			{
				DFS(j, i, &wolf, &sheep, R, C);//늑대가 V, 양이 K
			}
		}
	}
	cout << sheep << " " << wolf << "\n";

	return;
}

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

	int R, C;

	input_graph(&R, &C);
	find_answer(R, C);

	return 0;
}

0개의 댓글