#include <iostream>
#include <queue>
#include <string>
#include <cstring>
using namespace std;
const int MAX = 100001;
int n, k;
queue<pair<int, int>> q;
int visited[MAX];
int bfs(int i) {
int answer = 0;
if (i == k)
return answer;
q.push(make_pair(i, 0));
visited[i] = 1;
while (!q.empty()) {
int currentlocation = q.front().first;
int currenttime = q.front().second;
q.pop();
if (currentlocation == k) {
answer = currenttime;
break;
}
if ((currentlocation - 1) >= 0 ) {
if (visited[currentlocation-1] == -1) {
q.push(make_pair(currentlocation - 1, currenttime + 1));
visited[currentlocation-1] = 1;
}
}
if ( (currentlocation + 1) < MAX) {
if (visited[currentlocation+1] == -1) {
q.push(make_pair(currentlocation + 1, currenttime + 1));
visited[currentlocation+1] = 1;
}
}
if ( (currentlocation *2) < MAX) {
if (visited[currentlocation*2] == -1) {
q.push(make_pair(currentlocation * 2, currenttime + 1));
visited[currentlocation*2] = 1;
}
}
}
return answer;
}
int main(void) {
cin >> n >> k;
memset(visited, -1, sizeof(visited));
cout << bfs(n);
return 0;
}
'백준 알고리즘 > BFS' 카테고리의 다른 글
백준 2178번 C++ (0) | 2019.08.07 |
---|---|
백준 7576번 C++ (0) | 2019.02.24 |
백준 2178번 C++ (0) | 2019.02.19 |
백준 2589번 C++ (0) | 2019.01.14 |
백준 10026번 C++ (0) | 2019.01.13 |