Input: x =26, y =1Output: 3Explanation: We can make 26 equal to 1 by applying the following operations:1. Decrement x by 12. Divide x by 53. Divide x by 5It can be shown that 3is the minimum number of operations required to make 26 equal to 1.
Input: x =54, y =2Output: 4Explanation: We can make 54 equal to 2 by applying the following operations:1. Increment x by 12. Divide x by 113. Divide x by 54. Increment x by 1It can be shown that 4is the minimum number of operations required to make 54 equal to 2.
Input: x =25, y =30Output: 5Explanation: We can make 25 equal to 30 by applying the following operations:1. Increment x by 12. Increment x by 13. Increment x by 14. Increment x by 15. Increment x by 1It can be shown that 5is the minimum number of operations required to make 25 equal to 30.
classSolution {
funminimumOperations(x: Int, y: Int): Int {
val vis = mutableSetOf<Int>()
val q = ArrayDeque<Pair<Int, Int>>()
q.add(x to 0); vis.add(x)
while (q.isNotEmpty()) {
val(v, steps) = q.removeFirst()
if (v == y) return steps
for (nv in listOf(v - 1, v + 1)) {
if (nv in1..10000&& nv !in vis) {
q.add(nv to steps + 1); vis.add(nv)
}
}
if (v % 5==0&& v / 5>=1&& v / 5!in vis) {
q.add(v / 5 to steps + 1); vis.add(v / 5)
}
if (v % 11==0&& v / 11>=1&& v / 11!in vis) {
q.add(v / 11 to steps + 1); vis.add(v / 11)
}
}
return -1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from collections import deque
classSolution:
defminimumOperations(self, x: int, y: int) -> int:
vis = set([x])
q = deque([(x, 0)])
while q:
v, steps = q.popleft()
if v == y:
return steps
for nv in (v -1, v +1):
if1<= nv <=10000and nv notin vis:
q.append((nv, steps +1)); vis.add(nv)
if v %5==0and v //5>=1and v //5notin vis:
q.append((v //5, steps +1)); vis.add(v //5)
if v %11==0and v //11>=1and v //11notin vis:
q.append((v //11, steps +1)); vis.add(v //11)
return-1