[BOJ] 2146 다리 만들기

Time Lapse :NONE

2146.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
#include <memory.h>
#include <queue>
using namespace std;
int island = 2, N, ans = 987654321;
int map[100][100];
int dx[4] = { 0,1,0,-1 };
int dy[4] = { -1,0,1,0 };
bool visit[100][100];
void BFS(int _y, int _x) {
memset(visit, false, sizeof(visit));
queue<pair<int, int>> q;
visit[_y][_x] = true;
int _island = map[_y][_x];
q.emplace(_y, _x);
for (int i = 0; i < ans&&!q.empty(); ++i) {
int size = q.size();
for (int j = 0; j < size; ++j) {
int x = q.front().second;
int y = q.front().first;
q.pop();
for (int k = 0; k < 4; ++k) {
int nx = x + dx[k];
int ny = y + dy[k];
if (0 <= nx && nx < N && 0 <= ny && ny < N && !visit[ny][nx] && map[ny][nx] != _island) {
if (map[ny][nx]) {
ans = ans > i ? i : ans;
return;
}
visit[ny][nx] = true;
q.emplace(ny, nx);
}
}
}
}
}
int main() {
bool visit[100][100] = { false, };
queue<pair<int, int>> q;
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 && !visit[i][j]) {
q.emplace(i, j);
visit[i][j] = true;
map[i][j] = island;
while (!q.empty()) {
int x = q.front().second;
int y = q.front().first;
q.pop();
for (int k = 0; k < 4; ++k) {
int nx = x + dx[k];
int ny = y + dy[k];
if (0 <= nx && nx < N && 0 <= ny && ny < N && !visit[ny][nx] && map[ny][nx]) {
visit[ny][nx] = true;
q.emplace(ny, nx);
map[ny][nx] = island;
}
}
}
++island;
}
}
for(int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j) {
if (!map[i][j]) continue;
BFS(i, j);
}
printf("%d", ans);
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/07/30/PS/BOJ/2146/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.