1일1알

백준 3184번 양 C++ 본문

알고리즘

백준 3184번 양 C++

영춘권의달인 2023. 6. 30. 12:07

https://www.acmicpc.net/problem/3184

 

3184번: 양

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

www.acmicpc.net

 

bfs

 

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>

using namespace std;
using int64 = long long;

int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };

int r, c;
vector<vector<char>> board;
vector<vector<bool>> found;

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

	cin >> r >> c;
	board = vector<vector<char>>(r, vector<char>(c));
	found = vector<vector<bool>>(r, vector<bool>(c, false));
	for (int i = 0; i < r; i++) {
		for (int j = 0; j < c; j++) {
			cin >> board[i][j];
		}
	}
	int totalO = 0;
	int totalV = 0;
	for (int i = 0; i < r; i++) {
		for (int j = 0; j < c; j++) {
			if (board[i][j] == '#') continue;
			if (found[i][j]) continue;
			queue<pair<int, int>> q;
			q.push({ i,j });
			found[i][j] = true;
			int o = 0;
			int v = 0;
			while (!q.empty()) {
				auto curr = q.front();
				q.pop();
				if (board[curr.first][curr.second] == 'o') o++;
				else if (board[curr.first][curr.second] == 'v') v++;
				for (int k = 0; k < 4; k++) {
					int nextRow = curr.first + dRow[k];
					int nextCol = curr.second + dCol[k];
					if (nextRow >= r || nextRow < 0) continue;
					if (nextCol >= c || nextCol < 0) continue;
					if (board[nextRow][nextCol] == '#') continue;
					if (found[nextRow][nextCol]) continue;
					found[nextRow][nextCol] = true;
					q.push({ nextRow,nextCol });
				}
			}
			if (o > v) totalO += o;
			else totalV += v;
		}
	}
	cout << totalO << " " << totalV;
};