C++)
#include <iostream>
#include <algorithm>
#include <queue>
#define MAX_NUM 102
using namespace std;
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
string arr[MAX_NUM];
bool visited[MAX_NUM][MAX_NUM];
// 적록색약
int RGB(int n, bool flag) {
queue<pair<int, int>> q;
int cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (!visited[i][j]) {
visited[i][j] = true;
q.push( {i,j} );
cnt++;
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
char color = arr[x][y];
q.pop();
for (int k = 0; k < 4; k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
if (visited[nx][ny]) continue;
if (color == 'R' || color == 'G') {
if (flag) {
if ((arr[nx][ny] == 'R' || arr[nx][ny] == 'G') && !visited[nx][ny]) {
visited[nx][ny] = true;
q.push({ nx, ny });
}
}
else {
if (arr[nx][ny] == color && !visited[nx][ny]) {
visited[nx][ny] = true;
q.push({ nx,ny });
}
}
}
else {
if (arr[nx][ny] == color && !visited[nx][ny]) {
visited[nx][ny] = true;
q.push({ nx,ny });
}
}
}
}
}
}
}
return cnt;
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> arr[i];
int ans1 = RGB(n, false);
for (int i = 0; i < n; i++)
fill(visited[i], visited[i] + n, false);
int ans2 = RGB(n, true);
cout << ans1 << " " << ans2;
return 0;
}
Python)
import sys
from collections import deque
read = sys.stdin.readline
dx = [1,0,-1,0]
dy = [0,1,0,-1]
n = int(read().rstrip())
arr = [ [] * n for _ in range(n)]
visited = [ [False] * n for _ in range(n)]
for i in range(n):
arr[i] = list(read().rstrip())
q = deque()
def rgb():
cnt = 0
for i in range(n):
for j in range(n):
if not visited[i][j]:
visited[i][j] = True
q.append((i,j))
cnt += 1
while q:
x, y = q.popleft()
color = arr[x][y]
for k in range(4):
nx = x + dx[k]
ny = y + dy[k]
if nx < 0 or nx >= n or ny < 0 or ny >= n:
continue
elif arr[nx][ny] != color or visited[nx][ny]:
continue
visited[nx][ny] = True
q.append((nx,ny))
return cnt
ans1 = rgb()
visited = [ [False] * n for _ in range(n)]
for i in range(n):
for j in range(n):
if arr[i][j] == 'G':
arr[i][j] = 'R'
ans2 = rgb()
print(ans1, ans2)'백준 2 > 그래프' 카테고리의 다른 글
| [백준 10552] DOM (0) | 2020.12.08 |
|---|---|
| [백준 9466] 텀 프로젝트 (0) | 2020.12.08 |
| [백준 1743] 음식물 피하기 (0) | 2020.12.08 |
| [백준 2468] 안전영역 (C++/Python) (0) | 2020.12.08 |
| [백준 2583] 영역 구하기 (C++/Python) (0) | 2020.12.08 |