728x90
으... 너무 졸리다...
문제 1697번
https://www.acmicpc.net/problem/1697
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n, k;
bool visited[100001];
void bfs(int n) {
queue<pair<int, int>> q;
q.push({ n,0 });
while (!q.empty()) {
int x = q.front().first;
int cnt = q.front().second;
q.pop();
if (x == k) {
cout << cnt << endl;
break;
}
if (0 <= x - 1 && x - 1 <= 100000) {
if (!visited[x - 1]) {
visited[x - 1] = true;
q.push({ x - 1,cnt + 1 });
}
}
if (0 <= x + 1 && x + 1 <= 100000) {
if (!visited[x + 1]) {
visited[x + 1] = true;
q.push({ x + 1,cnt + 1 });
}
}
if (0 <= x * 2 && x * 2 <= 100000) {
if (!visited[x * 2]) {
visited[x * 2] = true;
q.push({ x * 2,cnt + 1 });
}
}
}
}
int main(void) {
cin >> n >> k;
visited[n] = true;
bfs(n);
}
728x90
'백준 > C++' 카테고리의 다른 글
[C++] 백준 10773번 - 제로 (2) | 2024.03.24 |
---|---|
[C++] 백준 4963번 - 섬의 개수 (2) | 2024.03.22 |
[C++] 백준 2178번 - 미로 탐색 (0) | 2024.03.07 |
[C++] 백준 2606번 - 바이러스 (3) | 2024.03.05 |
[C++] 백준 1260번 - DFS와 BFS (2) | 2024.03.04 |