Little Jay

[C++] 백준 3187번 - 양치기 꿍 본문

알고리즘/BOJ

[C++] 백준 3187번 - 양치기 꿍

Jay, Lee 2022. 7. 9. 17:46

간단했던 BFS 문제였는데 멍청하게 BFS 수행 조건을 잘못 줘서 30분동안 맞왜틀 하고 있던 문제였다. 

특별한 로직은 따로 없었고 양의 수 > 늑대 수 일때만 양의 수를 업데이트 시키는 것만 잘 파악했다면 크게 거렵지는 않았다. 

#include <bits/stdc++.h>
#define endl '\n'
using namespace std;

const int dx[] = { 1, -1, 0, 0 };
const int dy[] = { 0, 0, 1, -1 };

char board[255][255];
bool visited[255][255];
int r, c;

int wolves = 0, sheep = 0;

void bfs(int x, int y) {
	queue<pair<int, int>> q;
	q.push({ x, y });
	visited[x][y] = true;
	int wCnt = 0;
	int sCnt = 0;
	if (board[x][y] == 'v') wCnt++;
	if (board[x][y] == 'k') sCnt++;

	while (!q.empty()) {
		auto current = q.front(); q.pop();

		for (int dir = 0; dir < 4; dir++) {
			int ny = current.second + dy[dir];
			int nx = current.first + dx[dir];

			if (ny < 0 || nx < 0 || ny >= c || nx >= r) continue;
			if (visited[nx][ny] == false && board[nx][ny] != '#') {
				if (board[nx][ny] == 'v') wCnt++;
				if (board[nx][ny] == 'k') sCnt++;
				q.push({ nx, ny });
				visited[nx][ny] = true;
			}
		}
	}

	if (sCnt > wCnt) 
		sheep += sCnt;
	else 
		wolves += wCnt;
}

int main() {

	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);

	cin >> r >> c;
	for (int i = 0; i < r; i++) {
		for (int j = 0; j < c; j++) {
			cin >> board[i][j];
		}
	}

	for (int i = 0; i < r; i++) {
		for (int j = 0; j < c; j++) {
			if (board[i][j] != '#' && !visited[i][j]) 
				bfs(i, j);
		}
	}

	cout << sheep << " " << wolves << endl;

	return 0;
}
Comments