문제 출처 : https://www.acmicpc.net/problem/1697

<C++Code>

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
52
53
#include<iostream>
#include<queue>
using namespace std;
int n,m;
queue<pair<int,int> > q;
int v[100001];
 
void bfs(int start)
{
    
    q.push({0,start});
    v[start]=1;
    while(!q.empty())
    {
        int pox=q.front().second;
        int count=q.front().first;
        q.pop();
        v[pox]=1;
        if(pox==m)
        {
            cout<<count<<endl;
            break;
        }
        if(pox-1>=0&&v[pox-1]==0)
        {
            q.push({count+1,pox-1});
        }
        if(pox+1<=100000&&v[pox+1]==0)
        {
        q.push({count+1,pox+1});
        }
        if(pox*2<=100000&&v[pox*2]==0)
        {
            q.push({count+1,pox*2});
        }
        
        
        }
    
    }
 
 
 
int main(void)
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    cin>>n>>m;
    bfs(n);
    return 0;
    
}
cs

'백준 온라인 저지 > BFS, DFS (그래프)' 카테고리의 다른 글

13549번_숨바꼭질 3  (0) 2019.12.03
13913번_숨바꼭질 4(Bfs)  (0) 2019.12.02
7576번_토마토 (Bfs)  (0) 2019.11.27
11724번_연결 요소의 개수(Dfs,Bfs)  (0) 2019.11.27
2667번_단지번호붙이기(Bfs)  (0) 2019.11.26

+ Recent posts