Coding Test - cpp/BFS
[백준 3184: 양] - C++
에드윈H
2021. 3. 4. 17:04
#include <iostream>
#include <queue>
#include <string>
using namespace std;
char map[251][251];
int visited[251][251];
int dir[4][2] = {
{-1,0}
,{0,1}
,{1,0}
,{0,-1}
};
int r, c;
int vCnt = 0;
int oCnt = 0;
void bfs(int _x, int _y)
{
queue < pair<int, int>> q;
visited[_x][_y] = 1;
q.push({ _x,_y });
while (!q.empty())
{
int curX = q.front().first;
int curY = q.front().second;
q.pop();
for (int i = 0; i < 4; i++)
{
int nextX = curX + dir[i][0];
int nextY = curY + dir[i][1];
if (nextY < 0 || nextX < 0 || r <= nextX || c <= nextY)
continue;
if (!visited[nextX][nextY] && (map[nextX][nextY] == '.' || map[nextX][nextY] == 'o' || map[nextX][nextY] == 'v'))
{
visited[nextX][nextY] = 1;
q.push({ nextX,nextY });
if (map[nextX][nextY] == 'o')
oCnt++;
else if (map[nextX][nextY] == 'v')
vCnt++;
}
}
}
}
int main(void)
{
cin >> r >> c;
string n;
for (int i = 0; i < r; i++)
{
cin >> n;
for (int j = 0; j < c; j++)
{
map[i][j] = n[j];
}
}
bool bcheck = false;
int vCntTotal = 0;
int oCntTotal = 0;
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
bcheck = false;
if (map[i][j] == 'v' && !visited[i][j])
{
vCnt = 1;
oCnt = 0;
bfs(i, j);
bcheck = true;
}
else if (map[i][j] == 'o' && !visited[i][j])
{
vCnt = 0;
oCnt = 1;
bfs(i, j);
bcheck = true;
}
if (bcheck)
{
if (vCnt >= oCnt)
{
vCntTotal += vCnt;
}
else {
oCntTotal += oCnt;
}
}
}
}
cout << oCntTotal << " " << vCntTotal << '\n';
return 0;
}