๐ Self Study/๐ BaekJoon
๋ฐฑ์ค BaekJoon (์จ๋ฐ๊ผญ์ง, 1697๋ฒ) C++
UKHYUN22
2022. 1. 11. 16:52
728x90
BFS ์ฒ๋ผ ๊ฐ๋ฉด ๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ์ฐพ์ ์ ์๋ค. DFS์ฒ๋ผ ์๊ฐ์ ํ์๋ค. ์ฃผ๋ณ์ ๊ฐ ์ ์๋ ๊ณณ์ ๋ํ ๋ชจ๋ ๊ณ ๋ ค๋ฅผ ํ๋ฉด์ ์ํ๋ node์ ๋ง๋๋ฉด break ํ๊ฒ ํ๋ฉด ์๊ณ ๋ฆฌ์ฆ ๋.
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
vector<int> visited(100010, 0);
vector<int> path(100010, 0);
queue<int> q;
int start = 0, end = 0;
cin >> start >> end;
q.push(start);
visited[start] = 1;
while(!q.empty()) {
int node = q.front();
if(node == end) break;
q.pop();
if(visited[node+1] == 0 && node + 1 >= 0 && node + 1 < 100001) {
q.push(node+1);
visited[node+1] = 1;
path[node+1] = path[node] + 1;
}
if(visited[node-1] == 0 && node - 1 >= 0 && node - 1 < 100001) {
q.push(node-1);
visited[node-1] = 1;
path[node-1] = path[node] + 1;
}
if(visited[node*2] == 0 && node*2 >= 0 && node*2 < 100001){
q.push(node * 2);
visited[node*2] = 1;
path[node*2] = path[node] + 1;
}
}
cout << path[end];
return 0;
}