[백준] 1697번 : 숨바꼭질 - C++

강재원·2022년 12월 1일
0

[코딩테스트] C/C++

목록 보기
195/200



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

#include<iostream>
#include<queue>
#include<vector>
using namespace std;

static int check[100001];
static int n,k;

static void bfs(int a){
    queue<pair<int,int>> q;
    q.push(make_pair(a,0));
    check[a]=1;
    
    while(!q.empty()){
        int v1=q.front().first;
        int v2=q.front().second;
        q.pop();
        
        if(v1==k){
            cout << v2;
            return;
        }
        if(2*v1<=100000 && check[2*v1]==0){
            check[2*v1]=1;
            q.push(make_pair(2*v1,v2+1));
        }
        if(v1+1<=100000 && check[v1+1]==0){
            check[v1+1]=1;
            q.push(make_pair(v1+1,v2+1));
        }
        if(v1-1>=0 && check[v1-1]==0){
            check[v1-1]=1;
            q.push(make_pair(v1-1,v2+1));
        }
    }
}


int main() {
    cin >> n >> k;
    bfs(n);
}
profile
개념정리 & 문법 정리 & 알고리즘 공부

0개의 댓글