알고리즘/BOJ
[C++] 백준 10026번 - 적녹색약
Jay, Lee
2022. 8. 31. 20:15
BFS를 기반으로 하는 문제이다. 단순히 BFS를 두번 돌리면 되는데, 첫 번째는 정상적인 BFS로, 두 번째는 R==G일때도 통과되게 만들면 된다.
#include <bits/stdc++.h>
#define endl '\n'
#define pii pair<int, int>
using namespace std;
int t;
int n;
char graph[101][101];
bool visited[101][101];
const int dx[] = { 1, -1, 0, 0 };
const int dy[] = { 0, 0, 1, -1 };
int bfs(int x, int y, bool eye) {
visited[x][y] = true;
char target = graph[x][y];
queue<pii> q;
q.push({ x, y });
while (!q.empty()) {
auto cur = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
int nx = cur.first + dx[i];
int ny = cur.second + dy[i];
if (nx < 1 || ny < 1 || nx > n || ny > n) continue;
if (target != graph[nx][ny]) {
if (eye && (target == 'R' && graph[nx][ny] == 'G' || target == 'G' && graph[nx][ny] == 'R')) {
}
else continue;
}
if (visited[nx][ny]) continue;
q.push({ nx, ny });
visited[nx][ny] = true;
}
}
return 1;
}
void solve() {
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> graph[i][j];
}
}
int normal = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (!visited[i][j]) {
normal += bfs(i, j, false);
}
}
}
memset(visited, false, sizeof(visited));
int abnormal = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (!visited[i][j]) {
abnormal += bfs(i, j, true);
}
}
}
cout << normal << " " << abnormal << endl;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
t = 1;
while (t--) {
solve();
}
return 0;
}