알고리즘 문제
[백준] 3184번 양
feelcoding
2020. 2. 24. 23:01
728x90
https://www.acmicpc.net/problem/3184
3184번: 양
문제 미키의 뒷마당에는 특정 수의 양이 있다. 그가 푹 잠든 사이에 배고픈 늑대는 마당에 들어와 양을 공격했다. 마당은 행과 열로 이루어진 직사각형 모양이다. 글자 '.' (점)은 빈 필드를 의미하며, 글자 '#'는 울타리를, 'o'는 양, 'v'는 늑대를 의미한다. 한 칸에서 수평, 수직만으로 이동하며 울타리를 지나지 않고 다른 칸으로 이동할 수 있다면, 두 칸은 같은 영역 안에 속해 있다고 한다. 마당에서 "탈출"할 수 있는 칸은 어떤 영역에도 속하지
www.acmicpc.net
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() {
cin.tie(NULL);
int n, m;
cin >> n >> m;
vector<vector<char>> ground(n, vector<char>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> ground[i][j];
}
}
int sheepCount = 0;
int wolfCount = 0;
vector<vector<bool>> visited(n, vector<bool>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (ground[i][j] != '#' && !visited[i][j]) {
int sheep = 0;
int wolf = 0;
queue<pair<int, int>> q;
q.push(make_pair(i, j));
while (!q.empty()) {
pair<int, int> cur = q.front();
q.pop();
if (!visited[cur.first][cur.second]) {
if (ground[cur.first][cur.second] == 'o') sheep++;
if (ground[cur.first][cur.second] == 'v') wolf++;
visited[cur.first][cur.second] = true;
if (cur.first + 1 < n && !visited[cur.first + 1][cur.second] && ground[cur.first + 1][cur.second] != '#') {
q.push(make_pair(cur.first + 1, cur.second));
}
if (cur.first - 1 >= 0 && !visited[cur.first - 1][cur.second] && ground[cur.first - 1][cur.second] != '#') {
q.push(make_pair(cur.first - 1, cur.second));
}
if (cur.second + 1 < m && !visited[cur.first][cur.second + 1] && ground[cur.first][cur.second + 1] != '#') {
q.push(make_pair(cur.first, cur.second + 1));
}
if (cur.second - 1 >= 0 && !visited[cur.first][cur.second - 1] && ground[cur.first][cur.second - 1] != '#') {
q.push(make_pair(cur.first, cur.second - 1));
}
}
}
if (sheep > wolf) {
sheepCount += sheep;
}
else {
wolfCount += wolf;
}
}
}
}
cout << sheepCount << " " << wolfCount;
return 0;
}
728x90