[BOJ-Code] 17086 - 아기 상어 2

Posted by DHniyeo Blog on March 10, 2024

문제 링크

💡 너비 우선 탐색/브루트포스 알고리즘/그래프 이론/그래프 탐색

Memory 1236KB Time 88ms Code Length 1044B

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
#include <stdio.h>
#include <queue>
#include <tuple>
#include <string.h>
using namespace std;

int n, m;
int map[50][50];
int dy[] = { -1,-1,-1,0,0,1,1,1 };
int dx[] = { -1,0,1,-1,1,-1,0,1 };


int bfs(int a, int b) {
	int visited[50][50] = { 0 };
	queue<pair<int, int>> q;
	q.push({ a,b });
	visited[a][b] = 1;
	while (!q.empty()) {
		int y, x;
		tie(y, x) = q.front(); q.pop();

		if (map[y][x] == 1) {
			return  visited[y][x] - 1;
		}

		for (int i = 0; i < 8; i++) {
			int ny = y + dy[i];
			int nx = x + dx[i];
			if (ny >= n || nx >= m || ny < 0 || nx < 0) continue;
			if (visited[ny][nx] != 0) continue;
			visited[ny][nx] = visited[y][x] + 1;
			q.push({ ny,nx });
		}

	}

	return 0;
}


int main()
{
	scanf("%d %d", &n, &m);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			scanf(" %d", &map[i][j]);
		}
	}

	int max = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (map[i][j] == 0) {
				int tmp = bfs(i, j);
				if (max < tmp) {
					max = tmp;
				}
			}
		}
	}

	printf("%d", max);


}

이 코드는 2차원 배열로 표현된 지도에서 0과 1로 이루어진 영역을 탐색하고, 0으로 이루어진 영역 중에서 가장 먼 거리에 있는 1의 위치까지의 거리를 구하는 프로그램이다. 너비 우선 탐색(BFS) 알고리즘을 사용하여 0으로 이루어진 영역을 탐색하며, 1을 만나면 그 위치까지의 거리를 반환한다. 이를 모든 0으로 이루어진 영역에 대해 반복하여 최대 거리를 찾아 출력한다.