[BOJ-Code] 2146 - 다리 만들기

Posted by DHniyeo Blog on March 10, 2024

문제 링크

💡 너비 우선 탐색/그래프 이론/그래프 탐색

Memory 1884KB Time 72ms Code Length 1752B

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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include<stdio.h>
#include<algorithm>
#include<queue>
#include <string.h>

using namespace std;

int n;
int map[200][200];
int visited[200][200];

int dy[] = { -1,1,0,0 };
int dx[] = { 0,0,-1,1 };
void dfs(int y, int x, int label) {
	visited[y][x] = 1;
	map[y][x] = label;
	for (int i = 0; i < 4; i++) {
		int ny = y + dy[i];
		int nx = x + dx[i];
		if (ny >= n || nx >= n || ny < 0 || nx < 0) continue;
		if (map[ny][nx] == 0) continue;
		if (visited[ny][nx]) continue;

		dfs(ny, nx, label);
	}
}
struct INFO {
	int y, x;
};

int bfs(int label) {
	memset(visited, 0, sizeof(visited));
	queue<INFO> q;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (map[i][j] == label) {
				q.push({ i,j });
				visited[i][j] = 1;
			}
		}
	}
	int result = 0;
	while (!q.empty()) {
		int a = q.size();
		for (int i = 0; i < a; i++) {
			INFO tmp = q.front(); q.pop();
			for (int j = 0; j < 4; j++) {
				int ny = tmp.y + dy[j];
				int nx = tmp.x + dx[j];
				if (ny < 0 || ny >= n || nx < 0 || nx >= n) continue;
				if (map[ny][nx] != 0 && map[ny][nx] != label) return result;
				if (map[ny][nx] == 0 && visited[ny][nx] == 0) {
					visited[ny][nx] = 1;
					q.push({ ny,nx });
				}
			}
		}
		result++;
	}
	return 0;

}

int main()
{
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			scanf(" %d", &map[i][j]);
		}
	}
	// 맵 라벨링
	int label_cnt = 1;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (map[i][j] == 0) continue;
			if (visited[i][j] == 1) continue;
			dfs(i, j, label_cnt);
			label_cnt++;
		}
	}
	// 시작점은 하나이여야함.
	int min = 1e9;
	for (int i = 1; i < label_cnt; i++) {
		int tmp = bfs(i);
		if (min > tmp) min = tmp;
	}

	printf("%d\n", min);

}

이 코드는 입력으로 받은 2차원 배열을 탐색하면서 각 영역을 라벨링하고, 각 라벨링된 영역에서 다른 영역으로 가는 최소 거리를 구하는 프로그램이다.

입력으로 받은 2차원 배열을 탐색하면서 각 영역을 라벨링한다.

각 라벨링된 영역에서 bfs 함수를 호출하여 다른 영역으로 가는 최소 거리를 구한다.

최소 거리를 구한 후 출력한다.