백준알고리즘
뿌요뿌요
먼지의삶
2019. 8. 14. 17:53
#include<iostream>
#include<queue>
#include<cstdlib>
#include<cstring>
using namespace std;
int map[12][6];
bool d[12][6];
bool go[12];
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
int ans = 0;
bool keep = false;
void modi_map(){
for(int i = 0; i < 6; i++){
memset(go,false, sizeof(go));
for(int j = 0; j < 12; j++) {
if(map[j][i] != 0) {
go[j] = true;
}
}
for(int j = 11; j >= 0; j--){
if(go[j] == false){
for(int k = j-1; k >= 0; k--){
if(map[k][i] != 0){
map[j][i] = map[k][i];
map[k][i] = 0;
go[j] = true;
go[k] = false;
break;
}
}
}
}
}
}
void bfs(int x, int y, int value){
int v = value;
queue<pair<int, int>> q;
int sx = x; int sy = y;
q.push({x,y});
d[x][y] = true;
int t = 1;
while(!q.empty()){
x = q.front().first; y = q.front().second;
q.pop();
for(int i = 0; i <4; i++){
int nx = x+dx[i]; int ny = y+dy[i];
if(nx >= 0 && nx < 12 &&ny>=0 && ny < 6){
if(map[nx][ny] == v){
if(d[nx][ny] == false){
d[nx][ny] =true;
t+=1;
q.push({nx,ny});
}
}
}
}
}
if(t >= 4){
keep = true;
x = sx; y = sy;
queue<pair<int,int>> p;
p.push({x,y});
map[x][y]= 0;
while(!p.empty()){
x = p.front().first; y = p.front().second;
p.pop();
for(int i = 0; i < 4; i++){
int nx = x+dx[i]; int ny = y+dy[i];
if(nx >= 0 && nx < 12 &&ny>=0 && ny < 6){
if(map[nx][ny] == v){
map[nx][ny] = 0;
p.push({nx,ny});
}
}
}
}
}
}
int main(){
for(int i = 0; i < 12; i++){
for(int j = 0; j < 6; j++){
char x;
cin>>x;
if(x == 'R')
map[i][j] = 1;
if(x == 'Y')
map[i][j] = 2;
if(x == 'G')
map[i][j] = 3;
if(x == 'P')
map[i][j] = 4;
if(x== 'B')
map[i][j] = 5;
}
}
while(true) {
keep = false;
modi_map();
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 6; j++) {
if (map[i][j] != 0) {
memset(d, false, sizeof(d));
bfs(i, j, map[i][j]);
}
}
}
if(keep == false){
break;
}
ans++;
}
cout<<ans<<'\n';
}
BFS 문제