[BaekJoon] 2178번 - 미로 탐색 [Java][C++]
[BaekJoon] 2178번 - 미로 탐색 [Java][C++]
1. 아이디어
주어진 미로에서 이동할 수 있는 칸을 통해 $(1,\ 1)$ 에서 $(N,\ M)$ 까지 가는 최단거리를 구하는 문제로 사방탐색과 BFS를 활용하면 간단하게 해결할 수 있다. 2차원 배열로 미로가 표현됐으므로 사방탐색으로 다음에 이동할 후보지를 탐색하고, BFS는 큐의 크기만큼 탐색하면 등거리의 모든 후보를 탐색한다는 점에서 최단거리를 간단하게 구할 수 있다.
2. 코드
1. 풀이 [Java]
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
import java.io.*;
import java.util.*;
public class Main {
static int[] dr = {-1, 0, 1, 0};
static int[] dc = {0, 1, 0, -1};
static int n, m;
static char[][] grid;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
grid = new char[n][m];
for (int i = 0; i < n; i++) {
grid[i] = br.readLine().toCharArray();
}
System.out.println(bfs());
}
static int bfs() {
Queue<int[]> q = new ArrayDeque<>();
q.offer(new int[]{0, 0});
boolean[][] vis = new boolean[n][m];
vis[0][0] = true;
int dist = 1;
while (!q.isEmpty()) {
int sz = q.size();
while (sz-- > 0) {
int[] cur = q.poll();
if (cur[0] == n - 1 && cur[1] == m - 1) return dist;
for (int d = 0; d < 4; d++) {
int nr = cur[0] + dr[d];
int nc = cur[1] + dc[d];
if (nr < 0 || nr >= n || nc < 0 || nc >= m) continue;
if (grid[nr][nc] == '0' || vis[nr][nc]) continue;
q.offer(new int[]{nr, nc});
vis[nr][nc] = true;
}
}
dist++;
}
return -1;
}
}
2. 풀이 [C++]
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
#include <bits/stdc++.h>
using namespace std;
int dr[4] = {-1, 0, 1, 0};
int dc[4] = {0, 1, 0, -1};
int n, m;
char grid[101][101];
bool vis[101][101];
int bfs() {
queue<pair<int, int>> q;
q.push({0, 0});
vis[0][0] = true;
int dist = 1;
while (!q.empty()) {
int sz = q.size();
while (sz--) {
auto [r, c] = q.front();
q.pop();
if (r == n - 1 && c == m - 1) return dist;
for (int d = 0; d < 4; d++) {
int nr = r + dr[d];
int nc = c + dc[d];
if (nr < 0 || nr >= n || nc < 0 || nc >= m) continue;
if (grid[nr][nc] == '0' || vis[nr][nc]) continue;
q.push({nr, nc});
vis[nr][nc] = true;
}
}
dist++;
}
return -1;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> grid[i];
}
cout << bfs();
}
3. 디버깅
없음.
4. 참고
없음.
This post is licensed under CC BY 4.0 by the author.