BOJ

백준 2178 - 미로 탐색

yanJuicy 2019. 5. 31. 05:02
반응형

문제

https://www.acmicpc.net/problem/2178

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

 

풀이

bfs 탐색을 이용하여 (1,1) 에서 (N, M) 까지의 거리를 알아내면 된다. bfs 탐색을 할 때는 큐에 집어넣을 때 방문했다고 설정해야한다. 만약 큐에서 꺼낼 때 방문했다고 설정하면 중복해서 큐에 들어가는 좌표가 생길 수 있다(그래서 메모리 초과가 일어났다). bfs 탐색의 level이 바뀔 때 마다 result 값을 증가시킨다.

 

코드

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
92
93
94
95
96
97
#include <iostream>
#include <queue>
using namespace std;
 
bool graph[102][102];
char maze[101][101];
int N, M;
int result = 1;
queue<pair<intint>> q;
 
void findMin(int i, int j)
{
    graph[i][j] = false;
 
    if (graph[i - 1][j])
    {
        q.push(make_pair(i - 1, j));
        graph[i - 1][j] = false;
    }
    if (graph[i + 1][j])
    {
        q.push(make_pair(i + 1, j));
        graph[i + 1][j] = false;
    }
    if (graph[i][j - 1])
    {
        q.push(make_pair(i, j - 1));
        graph[i][j - 1= false;
    }
    if (graph[i][j + 1])
    {
        q.push(make_pair(i, j + 1));
        graph[i][j + 1= false;
    }
 
    while (!q.empty())
    {
        int len = q.size();
 
        for (int x = 0; x < len; x++)
        {
            i = q.front().first; j = q.front().second; q.pop();
            if (i == N && j == M)
            {
                result++;
                return;
            }
 
            if (graph[i - 1][j])
            {
                q.push(make_pair(i - 1, j));
                graph[i - 1][j] = false;
            }
            if (graph[i + 1][j])
            {
                q.push(make_pair(i + 1, j));
                graph[i + 1][j] = false;
            }
            if (graph[i][j - 1])
            {
                q.push(make_pair(i, j - 1));
                graph[i][j - 1= false;
            }
            if (graph[i][j + 1])
            {
                q.push(make_pair(i, j + 1));
                graph[i][j + 1= false;
            }
        }
        result++;
    }
}
 
int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
 
    cin >> N >> M;
 
    for (int i = 1; i <= N; i++)
        cin >> maze[i];
 
    for (int i = 1; i <= N; i++)
    {
        for (int j = 1; j <= M; j++)
        {
            if (maze[i][j - 1- '0') graph[i][j] = true;
        }
    }
 
    findMin(11);
    cout << result;
 
    return 0;
}
 
cs
반응형

'BOJ' 카테고리의 다른 글

백준 1700 - 멀티탭 스케줄링  (0) 2019.06.03
백준 2503 - 숫자 야구  (0) 2019.06.01
백준 2644 - 촌수계산  (0) 2019.05.30
백준 2193 - 이친수  (0) 2019.05.26
백준 1473 - 음식물 피하기  (0) 2019.05.23