[BOJ-Code] 2178 - 미로 탐색

Posted by DHniyeo Blog on March 9, 2024

문제 링크

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

Memory 1276KB Time 0ms Code Length 927B

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
#include <stdio.h>
#include <queue>
#include <algorithm>

using namespace std;
int visited[100][100] = { 0 };
int dy[] = { -1,1,0,0 };
int dx[] = { 0,0,-1,1 };
int n, m;
char map[100][101];
struct info {
	int y;
	int x;
	int cnt;
};

int bfs(int y, int x) {
	visited[y][x] = 1;
	queue<info> q;
	q.push({ y, x, 1 });

	int result = 0;
	while (!q.empty()) {
		info loc = q.front(); q.pop();
		if (loc.y == n-1 && loc.x == m-1) {
			return loc.cnt;
		}

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

	}
	return -1;
}

int main()
{

	scanf("%d %d", &n, &m);
	getchar();
	
	for (int i = 0; i < n; i++) {
		scanf("%s", map[i]);
		getchar();
	}
	int result = bfs(0,0);
	
	printf("%d\n", result);

}

이 코드는 너비 우선 탐색(BFS) 알고리즘을 사용하여 2차원 배열에서 출발 지점부터 도착 지점까지의 최단 거리를 구하는 프로그램이다.

먼저, 입력으로 주어지는 지도의 크기와 내용을 받아들인다.

그 다음, BFS 함수를 호출하여 출발 지점부터 도착 지점까지의 최단 거리를 계산한다.

BFS 함수는 큐를 사용하여 현재 위치에서 상하좌우로 이동하면서 갈 수 있는 위치를 탐색하고, 방문한 곳은 visited 배열을 통해 체크한다.

도착 지점에 도달하면 해당 위치까지의 이동 횟수를 반환하고, 도착 지점에 도달하지 못하면 -1을 반환한다.

마지막으로, 최단 거리를 출력한다.