첫째 줄에 가장 짧은 다리의 길이를 출력한다.
아이디어 구성까지는 좋았다.
영역별로 마스킹해서 하나하나 bfs로 다른 영역까지의 최소값을 구하는 식이었다.
그러나 계속 이상한 답이 나와서 구현하고나서도 30분넘게 디버깅만했다.
원인은... 다른영역찾았을때 bfs함수를 강종하고 다른 point에서 bfs를 수행하는데
전에 강종때문에 que가 초기화되지 않았던것...
#include <bits/stdc++.h>
using namespace std;
int x_direction[4] ={-1,1,0,0};
int y_direction[4] = {0,0,-1,1};
struct Point {
int x;
int y;
};
int n;
int nation[101][101];
bool visited[101][101];
queue<Point> que;
queue<Point> edge;
void masking(int mask);
int bfs();
int main(){
freopen("input.txt","r",stdin);
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n;
memset(nation, 0, sizeof(nation) );
memset(visited, false, sizeof(visited) );
int temp;
for(int i=0; i<n; ++i){
for(int j=0; j<n; ++j){
cin>>temp;
if(temp != 0){
nation[i][j] = temp;
}
}
}
int mask = 1;
for(int i=0; i<n; ++i){ //area masking
for(int j=0; j<n; ++j){
if( nation[i][j] && !visited[i][j] ){
visited[i][j] = true;
que.push({i,j});
masking(mask);
mask++;
//min_len = min_len < tmp ? min_len : tmp;
}
}
}
// for(int i=0; i<n; ++i){
// for(int j=0; j<n; ++j){
// cout<<nation[i][j]<<" ";
// }
// cout<<"\n";
// }
int min_len=200;
for(int i=0; i<n; ++i){ //find another area!
for(int j=0; j<n; ++j){
if(nation[i][j]!=0){
memset(visited,false, sizeof(visited));
que = queue<Point>();
que.push({i,j});
visited[i][j]=true;
//cout<<i<<", "<<j<<" to ";
temp = bfs() - 2;
min_len = min_len<temp ? min_len : temp; //save minimum length
}
}
}
cout<<min_len;
return 0;
}
int bfs(){
Point p;
int step_width;
int total_step=0;
int current_mask = nation[que.front().x][que.front().y];
//cout<<"what: "<<que.front().x<<", "<<que.front().y<<"\n";
while(!que.empty()){
step_width = que.size();
total_step ++;
for(int s=0; s<step_width; ++s){
p = que.front();
que.pop();
if( nation[p.x][p.y]!=current_mask && nation[p.x][p.y] != 0){
//cout<<" "<<p.x<<", "<<p.y<<" cost: "<<total_step<<"/ current: "<<current_mask<<" nation: "<<nation[p.x][p.y]<<"\n";
return total_step;
}
for(int i=0; i<4; ++i){
if(
(p.x+x_direction[i]>=0 && p.x+x_direction[i]<n) &&
(p.y+y_direction[i]>=0 && p.y+y_direction[i]<n) &&
(!visited[p.x+x_direction[i]][p.y+y_direction[i]]) &&
(nation[p.x+x_direction[i]][p.y+y_direction[i]] != current_mask) // is another place?
){
que.push({p.x+x_direction[i],p.y+y_direction[i]});
visited[p.x+x_direction[i]][p.y+y_direction[i]] = true;
}
}
}
}
//cout<<"nothing\n";
return 201;
}
void masking(int mask){
Point p;
while(!que.empty()){
p = que.front();
que.pop();
nation[p.x][p.y] = mask;
for(int i=0; i<4; ++i){
if(
(p.x+x_direction[i]>=0 && // >=0 important!
p.x+x_direction[i]<n) &&
(p.y+y_direction[i]>=0 &&
p.y+y_direction[i]<n) &&
(!visited[p.x+x_direction[i]][p.y+y_direction[i]]) &&
(nation[p.x+x_direction[i]][p.y+y_direction[i]] != 0)
){
visited[p.x+x_direction[i]][p.y+y_direction[i]] = true;
que.push({p.x+x_direction[i],p.y+y_direction[i]});
}
}
}
}