본문 바로가기

알고리즘/BFS 문제풀이

[B3055] - 탈출

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

물을 먼저 시간에 따라 이동시킨 후 고슴도치가가 그 시간내에 목적지에 도달할 수 있는지 확인하는 BFS문제이다.


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
#include<iostream>
#include<queue>
using namespace std;
char a[51][51];
int d[51][51];
int d2[51][51];
int dx[] = { 0,0,-1,1 };
int dy[] = { -1,1,0,0 };
int main() {
    int n, m;
    cin >> n>>m;
    int startx, starty;
    int endx, endy;
    queue<pair<intint>>q;
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
        for (int j = 0; j < m; ++j) {
            d[i][j] = -1;
            d2[i][j] = -1;
            if (a[i][j] == '*') {
                q.push({ i,j });
                d[i][j] = 0;
            }
            if(a[i][j]=='S'){
                startx = i;
                starty = j;
            }
            else if (a[i][j] == 'D') {
                endx = i;
                endy = j;
            }
        }
    }
    while (!q.empty()) {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
 
        for (int dir = 0; dir < 4; dir++) {
            int nx = x + dx[dir];
            int ny = y + dy[dir];
            if (nx >= 0 && nx < n&&ny >= 0 && ny < m) {
                if (a[nx][ny] == 'X'||a[nx][ny]=='D')
                    continue;
                if (d[nx][ny] == -1) {
                    d[nx][ny] = d[x][y] + 1;
                    q.push({ nx,ny });
                }
            }
        }
    }
    q.push({ startx,starty });
    d2[startx][starty] = 0;
    while (!q.empty()) {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        for (int dir = 0; dir < 4; dir++) {
            int nx = x + dx[dir];
            int ny = y + dy[dir];
            if (nx == endx && ny == endy) {
                cout << d[x][y] + 1 << '\n';
                return 0;
            }
            if (nx >= 0 && nx < n&&ny >= 0 && ny < m) {
                if (a[nx][ny] == 'X')
                    continue;
                if (d2[nx][ny] != -1)
                    continue;
                if (d2[x][y] + 1 < d[nx][ny])
                {
                    d2[nx][ny] = d2[x][y] + 1;
                    q.push({ nx,ny });
                }
            }
        }
    }
    if (d2[endx][endy] == -1
        cout << "KAKTUS" << '\n';
    else
        cout << d2[endx][endy] << '\n';
    
}
cs


'알고리즘 > BFS 문제풀이' 카테고리의 다른 글

[B7562] - 나이트의 이동  (0) 2018.08.30
[B5014] - 스타트링크  (0) 2018.08.26
[S1953] - [모의 SW 역량테스트] 탈주범검거  (0) 2018.08.25
[S1249] - 보급로  (0) 2018.08.25
[B14442]-벽 부수고 이동하기2  (0) 2018.08.24