- toc {:toc}
๋ฌธ์
์ ๋ก์์ฝ์ ๋นจ๊ฐ์๊ณผ ์ด๋ก์์ ์ฐจ์ด๋ฅผ ๊ฑฐ์ ๋๋ผ์ง ๋ชปํ๋ค. ๋ฐ๋ผ์, ์ ๋ก์์ฝ์ธ ์ฌ๋์ด ๋ณด๋ ๊ทธ๋ฆผ์ ์๋ ์ฌ๋์ด ๋ณด๋ ๊ทธ๋ฆผ๊ณผ๋ ์ข ๋ค๋ฅผ ์ ์๋ค.
ํฌ๊ธฐ๊ฐ NรN ์ธ ๊ทธ๋ฆฌ๋์ ๊ฐ ์นธ์ R(๋นจ๊ฐ), G(์ด๋ก), B(ํ๋) ์ค ํ๋๋ฅผ ์์น ํ ๊ทธ๋ฆผ์ด ์๋ค. ๊ทธ๋ฆผ์ ๋ช ๊ฐ์
๊ตฌ์ญ์ผ๋ก ๋๋์ด์ ธ ์๋๋ฐ, ๊ตฌ์ญ์ ๊ฐ์ ์์ผ๋ก ์ด๋ฃจ์ด์ ธ ์๋ค. ๋, ๊ฐ์ ์์์ด ์ํ์ข์ฐ๋ก ์ธ์ ํด ์๋ ๊ฒฝ์ฐ์ ๋ ๊ธ์๋ ๊ฐ์
๊ตฌ์ญ์ ์ํ๋ค. (์์์ ์ฐจ์ด๋ฅผ ๊ฑฐ์ ๋๋ผ์ง ๋ชปํ๋ ๊ฒฝ์ฐ๋ ๊ฐ์ ์์์ด๋ผ ํ๋ค)
์๋ฅผ ๋ค์ด, ๊ทธ๋ฆผ์ด ์๋์ ๊ฐ์ ๊ฒฝ์ฐ์
RRRBB
GGBBB
BBBRR
BBRRR
RRRRR
์ ๋ก์์ฝ์ด ์๋ ์ฌ๋์ด ๋ดค์ ๋ ๊ตฌ์ญ์ ์๋ ์ด 4 ๊ฐ์ด๋ค. (๋นจ๊ฐ 2, ํ๋ 1, ์ด๋ก 1) ํ์ง๋ง, ์ ๋ก์์ฝ์ธ ์ฌ๋์ ๊ตฌ์ญ์ 3 ๊ฐ ๋ณผ ์ ์๋ค. (๋นจ๊ฐ - ์ด๋ก 2, ํ๋ 1)
๊ทธ๋ฆผ์ด ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ก์ ๋, ์ ๋ก์์ฝ์ธ ์ฌ๋์ด ๋ดค์ ๋์ ์๋ ์ฌ๋์ด ๋ดค์ ๋ ๊ตฌ์ญ์ ์๋ฅผ ๊ตฌํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค.
์ ๋ ฅ
์ฒซ์งธ ์ค์ N ์ด ์ฃผ์ด์ง๋ค. (1 โค N โค 100)
๋์งธ ์ค๋ถํฐ N ๊ฐ ์ค์๋ ๊ทธ๋ฆผ์ด ์ฃผ์ด์ง๋ค.
์ถ๋ ฅ
์ ๋ก์์ฝ์ด ์๋ ์ฌ๋์ด ๋ดค์ ๋์ ๊ตฌ์ญ์ ๊ฐ์์ ์ ๋ก์์ฝ์ธ ์ฌ๋์ด ๋ดค์ ๋์ ๊ตฌ์ญ์ ์๋ฅผ ๊ณต๋ฐฑ์ผ๋ก ๊ตฌ๋ถํด ์ถ๋ ฅํ๋ค.
์ถ์ฒ:https://www.acmicpc.net/problem/10026
ํ์ด
์ผ๋ฐ์ธ์ ๊ตฌ๋ถ์ ํ๊ณ ๋ค์ ์ ๋ก์์ฝ์ ๊ตฌ๋ถ์ ๊ณ์ฐํ์ฌ 2 ๋ฒ BFS ๋ฅผ ์ฌ์ฉํ๋ค.
2 ๋ฒ ์ฌ์ฉํ๋ฉด์ BFS ๋ฅผ ํจ์๋ก ๋ง๋ค์์ผ๋ฉด ๋ ๊ฐํธํ๊ณ ๊น๋ํ์ง ์์์๊น ํ๋ ์๊ฐ์ด ๋ค์๋ค.
ํจ์ ์ ์ ์ฐ์ตํ๊ธฐ
#include <bits/stdc++.h>
using namespace std;
#define X first
#define Y second
string board[105];
int n;
int dx[4] = {0, -1, 0, 1};
int dy[4] = {-1, 0, 1, 0};
int Nvis[105][105];
int Bvis[105][105];
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
char color = ' ';
for(int i = 0; i < n; i++){
cin >> board[i];
}
queue<pair<int, int>> q;
int normal = 1;
for(int i = 0; i < n; i++){ // ์ผ๋ฐ ์ฌ๋
for(int j = 0; j < n; j++){
if(Nvis[i][j] >= 1) continue; // ์ฌ๊ธฐ์ ๊ฐ์ ์์ผ ๋ continueํด์ผํ๋ ์ค
q.push({i, j}); // ์์์ง๋ง ๋ฐ์์ ๊ฑธ๋ฌ์ฃผ๊ธฐ์ ํ์ ์๋ค.
Nvis[i][j] = normal++;
color = board[i][j];
while(!q.empty()){ // ๊ฐ์ ์๊น ํ์ธ
auto cur = q.front(); q.pop();
for(int dir = 0; dir < 4; dir++){
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if(nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
if(Nvis[nx][ny] >= 1 || board[cur.X][cur.Y] != board[nx][ny]) continue;
Nvis[nx][ny] = Nvis[cur.X][cur.Y];
q.push({nx, ny});
}
}
}
}
normal--;
cout << normal << ' ';
for(int i = 0; i < n; i++) { // ๋
น์์ ๋นจ๊ฐ๊ณผ ๊ฐ๊ฒ
for(int j = 0; j < n; j++) {
if(board[i][j] == 'G'){
board[i][j] = 'R';
}
}
}
int blind = 1;
color = ' ';
for(int i = 0; i < n; i++){ // ์ ๋ก์์ฝ์ BFS
for(int j = 0; j < n; j++){
if(Bvis[i][j] >= 1) continue;
q.push({i, j});
Bvis[i][j] = blind++;
color = board[i][j];
while(!q.empty()){ // ๊ฐ์ ์๊น ํ์ธ
auto cur = q.front(); q.pop();
for(int dir = 0; dir < 4; dir++){
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if(nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
if(Bvis[nx][ny] >= 1 || board[cur.X][cur.Y] != board[nx][ny]) continue;
Bvis[nx][ny] = Bvis[cur.X][cur.Y]; q.push({nx, ny}); }
}
}
}
/*
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cout << Bvis[i][j];
}
cout << endl;
}
*/
cout << blind-1;
}