반응형

문제 링크 : https://www.acmicpc.net/problem/1697

 

1697번: 숨바꼭질

문제 수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가

www.acmicpc.net

> 풀이

BFS 를 사용하여 수빈이가 이동하는 경우를 계산해 봅시다

#include <cstdio>
#include <vector>
#include <queue>
#include <climits>
#define MAX 100000
using namespace std;

int N, K, res = INT_MAX;
queue<pair<int, int>> bfs;
bool check[100001];

int main(void) {
        scanf("%d %d", &N, &K);
      
        if (N >= K) {
                printf("%d", N - K);
                return 0;
        }

        bfs.push({N, 0});
        while (!bfs.empty()) {
                auto a = bfs.front();
                int x = a.first, cnt = a.second;
                bfs.pop();
                
                if (x == K) {
                        res = min(res, cnt);
                        continue;
                }

                if (cnt > res) continue;

                if (x > 0 && x * 2 <= MAX && !check[x * 2]) {
                        check[x * 2] = true;
                        bfs.push({x * 2, cnt + 1});
                }
                if (x + 1 <= MAX && x < K && !check[x + 1]) {
                        check[x + 1] = true;
                        bfs.push({x + 1, cnt + 1});
                }
                if (x - 1 <= MAX && x - 1 >= 0 && !check[x - 1]) {
                        check[x - 1] = true;
                        bfs.push({x - 1, cnt + 1});
                }
        }
        printf("%d", res);
        return 0;
}

(개발 환경 : vs code)

반응형

+ Recent posts