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;
}
'๐ Self Study > ๐ BaekJoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค BaekJoon (์คํํธ๋งํฌ, 5014๋ฒ) C++ (0) | 2022.01.11 |
---|---|
๋ฐฑ์ค BaekJoon (์คํํธ๋งํฌ, 5014๋ฒ) C++ (0) | 2022.01.11 |
๋ฐฑ์ค BaekJoon (ํ ๋งํ , 7569๋ฒ) C++ (0) | 2022.01.11 |
๋ฐฑ์ค BaekJoon(์ด์ ๊ณ์ฐ, 2644๋ฒ) C++ (0) | 2022.01.10 |
๋ฐฑ์ค BaekJoon (DFS์ BFS, 1260) C++ (0) | 2022.01.05 |