-
Notifications
You must be signed in to change notification settings - Fork 160
/
Catchcow.cpp
72 lines (51 loc) · 1.09 KB
/
Catchcow.cpp
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
/*
Given two integers n and k, there are three operations n-1, n+1 and n*2.
Calculate the minimal number of operations such that n == k.
*/
/*
solution: BFS. It is similar to a problem where we want to find the shortest path from n to k.
O(k-n) time, O(k) space
*/
#include<iostream>
#include <queue>
using namespace std;
struct Point {
int value, step;
};
int Operation(int n,int choice) {
switch (choice) {
case 0:return n-1;
case 1:return n+1;
case 2:return n*2;
}
}
int MinimalOperations(int start, int end, bool visit[]) {
visit[start] = true;
queue <Point> q;
Point s,e;
s.value = start;
s.step = 0;
q.push(s);
while (!q.empty()) {
s = q.front();
q.pop();
if (s.value == end) { //reach end
break;
}
for (int i=0;i<3;i++) {
e.value = Operation(s.value, i);
e.step = s.step + 1;
if (e.value >= 0 && e.value <= 10000 && visit[e.value] == false) {
q.push(e);
visit[e.value]=true;
}
}
}
return s.step;
}
int main(){
int n = 5, k = 80;
bool visit[10000] = {0};
cout<<MinimalOperations(n, k, visit)<<endl;
return 0;
}