본문 바로가기
알고리즘/BFS

1697 숨바꼭질

by tryotto 2020. 1. 14.
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
#include <stdio.h>
#include <queue>
#include <utility>
 
using namespace std;
 
int dx[3= { -1,1 };
 
int bfs(int n, int k) {
    queue<pair<intint>> q;
    q.push(make_pair(0, n));
 
    int chk[200001= { 0 };
    while (!q.empty()) {
        int len = q.front().first;
        int x = q.front().second;
 
        q.pop();
        if (x == k) {
            return len;
        }
                
        for (int i = 0; i < 3; i++) {
            int xx;
            if (i == 2) {
                xx = x * 2;
            }
            else {
                xx = x + dx[i];
            }
 
            if (xx < 0 || xx>200000)
                continue;
            if (chk[xx] == 1)
                continue;
 
            chk[xx] = 1;
            q.push(make_pair(len+1, xx));
        }
    }
}
 
int main() {
    int n, k;
    scanf("%d %d"&n, &k);
 
    printf("%d",bfs(n, k));
}
cs



배열 메모리 초과를 해결하는 것이 관건이었다.
200000을 초과하는 경우, 아예 고려하지 않는 방식을 취했다. 
100000 이상을 threshold로 설정했을 경우, 틀릴수도 있으니 주의하기


'알고리즘 > BFS' 카테고리의 다른 글

2146 다리만들기  (0) 2020.01.18
7569 토마토  (0) 2020.01.14
7562 나이트의 이동  (0) 2020.01.14
7576 토마토  (0) 2020.01.14
2178 미로 탐색  (0) 2020.01.13