반응형

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

 

17836번: 공주님을 구해라!

용사는 마왕이 숨겨놓은 공주님을 구하기 위해 (N, M) 크기의 성 입구 (1,1)으로 들어왔다. 마왕은 용사가 공주를 찾지 못하도록 성의 여러 군데 마법 벽을 세워놓았다. 용사는 현재의 가지고 있는

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. visited [ y ][ x ][ gram ] 배열을 만들어 방문을 기록해 줍니다.

 

2. bfs를 이용하여 (1, 1)에서 (N, M)까지 이동합니다.

 

3. 이동할 때까지 걸린 시간이 T를 넘지 않으면 시간을 출력하고, 그렇지 않으면 Fail을 출력합니다.

 

[ 소스코드 ]

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
#include<iostream>
#include<queue>
 
using namespace std;
 
int N, M, T;
int arr[101][101];
int visited[101][101][2];
int dy[4= { -1,1,0,0 };
int dx[4= { 0,0,-1,1 };
 
struct node {
    int y;
    int x;
    int cnt;
    int gram;
};
 
int main()
{
    scanf("%d %d %d"&N, &M, &T);
 
    for (int i = 1; i <= N; i++) {
        for (int j = 1; j <= M; j++) {
            scanf("%d"&arr[i][j]);
        }
    }
 
    queue<node> q;
    q.push({ 1,1,0,false });
    visited[1][1][0= 1;
 
    while (!q.empty()) {
        const int y = q.front().y;
        const int x = q.front().x;
        const int cnt = q.front().cnt;
        const int gram = q.front().gram;
        q.pop();
 
        if (cnt > T) continue;
 
        if (y == N && x == M) {
            printf("%d", cnt);
            return 0;
        }
 
        for (int i = 0; i < 4; i++) {
            const int yy = y + dy[i];
            const int xx = x + dx[i];
 
            if (yy > 0 && yy <= N && xx > 0 && xx <= M) {
                if ((arr[yy][xx] == 1 && gram == true|| arr[yy][xx] == 0) {
                    if (visited[yy][xx][gram] != 1) {
                        visited[yy][xx][gram] = 1;
                        q.push({ yy,xx,cnt + 1,gram });
                    }
                }
                else if (arr[yy][xx] == 2) {
                    if (visited[yy][xx][1!= 1) {
                        visited[yy][xx][1= 1;
                        q.push({ yy,xx,cnt + 1,1 });
                    }
                }
 
            }
        }
    }
 
    printf("Fail");
}
cs
반응형

+ Recent posts