12791번 - 돌다리
간단한 BFS문제
나올 수 있는 8가지 경우를 큐에 포함시켜서 문제를 풀면된다.
<정답 코드>
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | #include<iostream> #include<queue> using namespace std; int a, b, n, m; int dist[100001]; bool check(int now) { return (now <= 100000 && now >= 0 && dist[now]==0); } int main() { cin >> a >> b >> n >> m; queue<int> q; q.push(n); dist[n] = 0; while (!q.empty()) { int now = q.front(); q.pop(); if (now == m) break; if (check(now + 1)) { q.push(now + 1); dist[now + 1] = dist[now] + 1; } if (check(now - 1)) { q.push(now - 1); dist[now - 1] = dist[now] + 1; } if (check(now + a)) { q.push(now + a); dist[now + a] = dist[now] + 1; } if (check(now - a)) { q.push(now - a); dist[now - a] = dist[now] + 1; } if (check(now + b)) { q.push(now + b); dist[now + b] = dist[now] + 1; } if (check(now - b)) { q.push(now - b); dist[now - b] = dist[now] + 1; } if (check(now * a)) { q.push(now * a); dist[now * a] = dist[now] + 1; } if (check(now * b)) { q.push(now * b); dist[now * b] = dist[now] + 1; } } cout << dist[m] << endl; return 0; } | cs |
반응형