이 문제는 간단한 그래프 탐색 문제다. 나는 가벼운 마음을 갖고 DFS로 풀었는데 생각보다 쉽지 않았다.
그래서 수많은 시행착오 후에 알게 됐는데, M이 가로가 아니라 N이 가로였다. 나는 그래프 문제 풀 때 항상 M을 가로로 했는데 선입견에 의해 틀린 것이었다. 그래도 풀고 나니 후련하다.
#include <bits/stdc++.h>
using namespace std;
char Map[101][101];
int n, m;
int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0 , -1 };
bool Check(int x, int y) {
return x < 0 || y < 0 || x >= n || y >= m;
}
int dfs(int x, int y, char v) {
int ret = 1;
Map[x][y] = 0; //이렇게 하면 굳이 visited를 만들지 않아도 방문 처리를 할 수 있음
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (Map[nx][ny] == v && !Check(nx, ny))
ret += dfs(nx, ny, v);
}
return ret;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
int res, a1 = 0, a2 = 0;
cin >> m >> n; //N이 가로였다니..
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> Map[i][j];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (Map[i][j] == 'W') res = dfs(i, j, 'W'), a1 += res; //W면 W인 걸 찾고
else if (Map[i][j] == 'B') res = dfs(i, j, 'B'), a2 += res; //B면 B인 걸 찾는다.
}
}
cout << a1 << ' ' << a2;
}