ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 12851 숨바꼭질 2 -BFS
    알고리즘/백준 2019. 3. 12. 22:01

    1. 문제



    2. 코드

    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
    #include <stdio.h>
    #include <queue>
    #include <iostream>
    #define _CRT_SECURE_NO_WARNINGS
    using namespace std;
     
    const int MAX = 100001;
     
    bool visit[MAX];
     
    int cnt;
    int ans;
     
    int main()
    {
        int N, K;
        scanf("%d %d"&N, &K);
        queue<pair<int,int>> q;
        
        q.push(make_pair(N,0));
        visit[N] = true;
     
        while (!q.empty())
        {    
            int cur = q.front().first;
            int curSec = q.front().second;
            q.pop();
     
            visit[cur] = true;
                
            if (ans && ans == curSec && cur == K) {
                cnt++;
            }
     
     
            if (!ans && cur == K) {
                ans = curSec;
                cnt++;
            }
     
            if (cur + 1 < MAX && !visit[cur+1])
                q.push(make_pair(cur+1, curSec +1));
            if (cur - 1 >= 0 && !visit[cur-1])
                q.push(make_pair(cur - 1, curSec + 1));
            if (cur * 2 < MAX && !visit[cur*2])
                q.push(make_pair(cur * 2, curSec + 1));
        }
        printf("%d\n", ans);
        printf("%d\n", cnt);
    }
     
    cs


    3. 후기

    1 7 의 경우 경로는 총 네 가지이다. 

    1 2(+1) 3 6 7

    1 2(+1) 4 8 7

    1 2(*2) 3 6 7

    1 2(*2) 4 8 7




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

    9328 열쇠  (0) 2019.03.15
    9376 탈옥  (0) 2019.03.14
    2251 물통  (0) 2019.03.12
    1525 퍼즐  (0) 2019.03.12
    9019 DSLR  (0) 2019.03.11
Designed by Tistory.