[LeetCode] Minimum Operations to Convert Number

2059. Minimum Operations to Convert Number

You are given a 0-indexed integer array nums containing distinct numbers, an integer start, and an integer goal. There is an integer x that is initially set to start, and you want to perform operations on x such that it is converted to goal. You can perform the following operation repeatedly on the number x:

If 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x to any of the following:

  • x + nums[i]
  • x - nums[i]
  • x ^ nums[i] (bitwise-XOR)

Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward.

Return the minimum number of operations needed to convert x = start into goal, and -1 if it is not possible.

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
class Solution {
public:
int minimumOperations(vector<int>& A, int start, int goal) {
queue<int> q;
q.push(start);
unordered_set<int> vis;
vis.insert(start);
int res = 1;
while(!q.empty() and res <= 1000) {
int sz = q.size();
while(sz--) {
auto n = q.front(); q.pop();
for(auto& a : A) {
if(a + n == goal or n - a == goal or (a ^ n) == goal) {
return res;
}
if(0 <= a + n and a + n <= 1000 and !vis.count(a+n)) {
vis.insert(a+n);
q.push(a+n);
}
if(0 <= n - a and n - a <= 1000 and !vis.count(n - a)) {
vis.insert(n-a);
q.push(n-a);
}
if(0 <= (a ^ n) and (a ^ n) <= 1000 and !vis.count(a ^ n)) {
vis.insert(a^n);
q.push(a^n);
}
}
}
res++;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/27/PS/LeetCode/minimum-operations-to-convert-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.