๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/๋ฐฑ์ค€

[๋ฐฑ์ค€] 1697 ์ˆจ๋ฐ”๊ผญ์งˆ BFS

by Jouureee 2021. 4. 21.

๋ฌธ์ œ :

www.acmicpc.net/problem/1697

 

1697๋ฒˆ: ์ˆจ๋ฐ”๊ผญ์งˆ

์ˆ˜๋นˆ์ด๋Š” ๋™์ƒ๊ณผ ์ˆจ๋ฐ”๊ผญ์งˆ์„ ํ•˜๊ณ  ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ํ˜„์žฌ ์  N(0 ≤ N ≤ 100,000)์— ์žˆ๊ณ , ๋™์ƒ์€ ์  K(0 ≤ K ≤ 100,000)์— ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ๊ฑท๊ฑฐ๋‚˜ ์ˆœ๊ฐ„์ด๋™์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋งŒ์•ฝ, ์ˆ˜๋นˆ์ด์˜ ์œ„์น˜๊ฐ€ X์ผ

www.acmicpc.net

๋ถ„์„ :

ํ’€์ง€ ๋ชปํ–ˆ๋˜ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค ๐Ÿคญ ์ฒ˜์Œ์—” ์žฌ๊ท€๋กœ ์ ‘๊ทผํ•˜๋‹ค ๊ฐ€๊นŒ์šด ๊ฑฐ๋ฆฌ๋จผ์ € ํƒ์ƒ‰ ํ•ด์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์„ ๊นจ๋‹ฌ์•˜๋‹ค. 

์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ์ฐพ๋Š” bfs ๋ฌธ์ œ์ด๋ฏ€๋กœ queue๋ฅผ ์‚ฌ์šฉํ–ˆ๊ณ  ์ˆ˜๋นˆ์ด์˜ ์›€์ง์ž„ moving ๋ฐฐ์—ด์— ๋„ฃ์€ ๋’ค visit์— ์›€์ง์ธ ๊ฑฐ๋ฆฌ๋งŒํผ์„ +1 ํ•ด์ค˜์„œ ๋ˆ„์ ์‹œ์ผฐ๋‹ค.

๊ทธ๋ฆฌ๊ณ  k์— ๋„๋‹ฌํ–ˆ์„ ๋•Œ ๋ˆ„์ ๋œ ๊ฐ’์„ ์ถœ๋ ฅ์‹œํ‚ค๋ฉด ๋!!

 

 

c++ ์ฝ”๋“œ :

//
//  1697_hide_seek.cpp
//  SOMA๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป
//
//  Created by JoSoJeong on 2021/02/21.
//

#include <stdio.h>
#include <iostream>
#include <queue>
#include <string.h>


using namespace std;
#define MAX 100000
int visit[MAX + 1];
int n, k;
int moving[3] = { - 1, 1, 2}; //walk, jump

void hide_and_seek_bfs(int num){
    queue<int> q;
    q.push(num);
    visit[num] = 0;
    
    if(num == k){
        cout << 0 << '\n';
    }
    
    while(!q.empty()){
        int temp = q.front();
        int next;
        q.pop();
        
        for(int i = 0; i < 3; i++){
            if(i == 2) next = moving[i] * temp;
            else next = moving[i] + temp;
            
            //์˜ˆ์™ธ ์ฒ˜๋ฆฌ
            if(next < 0 || next > 100000) continue;
            if(visit[next] != -1) continue;
            
            q.push(next);
            visit[next] = visit[temp] + 1;
            
            if(next == k){
                cout << visit[next] << '\n';
                break;
            }
            
            
        }
    }
}



int main(){
    memset(visit, -1, sizeof(visit));
    cin >> n >> k;
    hide_and_seek_bfs(n);
    return 0;
}

๋Œ“๊ธ€