알고리즘/BFS 문제풀이

[B2206]-벽 부수고 이동하기

tongnamuu 2018. 8. 24. 20:18

이번에 풀 문제는

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

입니다.

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
#include <cstdio>
#include <queue>
using namespace std;
 
int main()
{
    int n, m;
    scanf("%d %d"&n, &m);
    int a[1001][1001];
    int d[1001][1001][2= { 0, };
    int dx[] = { 0,0,-1,};
    int dy[] = { -1,1,0,};
    int ans = 0;
    queue<pair<pair<intint>int>>q;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            scanf("%1d"&a[i][j]);
        }
    }
    q.push({ { 0}, });
    d[0][0][0= 1;
    while (!q.empty())
    {
        int x = q.front().first.first;
        int y = q.front().first.second;
        int z = q.front().second;
        q.pop();
        for (int k = 0; k < 4; k++)
        {
            int nx = x + dx[k];
            int ny = y + dy[k];
            if (nx < n && nx >= && ny < m && ny >= 0)
            {
                if (a[nx][ny] == && d[nx][ny][z] == 0)
                {
                    d[nx][ny][z] = d[x][y][z] + 1;
                    q.push({ {nx,ny},z });
                }
                if (a[nx][ny] == && z == && d[nx][ny][z + 1== 0)
                {
                    d[nx][ny][z + 1= d[x][y][z] + 1;
                    q.push({ { nx,ny },z + });
                }
            }
        }
    }
    if (d[n - 1][m - 1][0!= && d[n - 1][m - 1][1!= 0)
    {
        if (d[n - 1][m - 1][0> d[n - 1][m - 1][1])
            ans = d[n - 1][m - 1][1];
        else
            ans = d[n - 1][m - 1][1];
    }
    else if (d[n - 1][m - 1][0!= 0)
        ans = d[n - 1][m - 1][0];
    else if (d[n - 1][m - 1][1!= 0)
        ans = d[n - 1][m - 1][1];
    else
        ans = -1;
    printf("%d\n", ans);
}
cs