반응형
단지번호 붙이기 + 짧은 다리 만들기 dfs + bfs
#define CRT_SECURE_NO_WARNING
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
int map[101][101];
int N;
int islandNum = 2;
int dy[4] = { 1,0,-1,0 };
int dx[4] = { 0,1,0,-1 };
int res=987654321;
void dfs(int x, int y, int num) {
map[x][y] = num;
for (int i = 0; i < 4; i++) {
int cx = x + dx[i];
int cy = y + dy[i];
if (cx < 0 || cy < 0 || cx >= N || cy >= N || map[cx][cy] != 1) continue;
dfs(cx, cy, num);
}
}
int bfs(int x, int y, int num) {
queue <pair<pair<int, int>, int>> q;
q.push({ {x,y},0 });
int visited[101][101] = { 0, };
while (!q.empty()) {
int nx = q.front().first.first;
int ny = q.front().first.second;
int cnum = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {
int cx = nx + dx[i];
int cy = ny + dy[i];
if (cx < 0 || cy < 0 || cx >= N || cy >= N || map[cx][cy] == num || visited[cx][cy] == 1) continue;
if (map[cx][cy] != 0) return cnum;
visited[cx][cy] = 1;
q.push({ {cx,cy},cnum+1 });
}
}
return 987654321;
}
int main() {
scanf("%d", &N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
scanf("%d", &map[i][j]);
}
}
//단지번호 붙이기
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (map[i][j] == 1) {
dfs(i, j, islandNum);
islandNum++;
}
}
}
//짧은 다리 만들기
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (map[i][j] != 0) {
res = min(res, bfs(i, j, map[i][j]));
}
}
}
printf("%d", res);
return 0;
}
반응형