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 _theminimum number of operations needed to convert _x = startintogoal, and-1if it is not possible.
Input: nums =[3,5,7], start =0, goal =-4Output: 2Explanation: We can go from 0->3->-4with the following 2 operations.-0+3=3-3-7=-4Note that the last operation sets x out of the range 0<= x <=1000, which is valid.
We want the minimum number of operations to reach goal from start using allowed operations. BFS explores all possible states in increasing order of steps, ensuring the shortest path is found.
import java.util.*;
classSolution {
publicintminimumOperations(int[] nums, int start, int goal) {
Queue<int[]> q =new LinkedList<>();
boolean[] vis =newboolean[1001];
q.add(newint[]{start, 0});
vis[start]=true;
while (!q.isEmpty()) {
int[] p = q.poll();
int x = p[0], step = p[1];
for (int v : nums) {
for (int y : newint[]{x + v, x - v, x ^ v}) {
if (y == goal) return step + 1;
if (0 <= y && y <= 1000 &&!vis[y]) {
vis[y]=true;
q.add(newint[]{y, step + 1});
}
}
}
}
return-1;
}
}
import java.util.LinkedList
classSolution {
funminimumOperations(nums: IntArray, start: Int, goal: Int): Int {
val vis = BooleanArray(1001)
val q = LinkedList<Pair<Int, Int>>()
q.add(start to 0)
vis[start] = truewhile (q.isNotEmpty()) {
val(x, step) = q.poll()
for (v in nums) {
for (y in listOf(x + v, x - v, x xor v)) {
if (y == goal) return step + 1if (y in0..1000&& !vis[y]) {
vis[y] = true q.add(y to step + 1)
}
}
}
}
return -1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from collections import deque
classSolution:
defminimumOperations(self, nums: list[int], start: int, goal: int) -> int:
vis = [False] *1001 q = deque([(start, 0)])
vis[start] =Truewhile q:
x, step = q.popleft()
for v in nums:
for y in (x + v, x - v, x ^ v):
if y == goal:
return step +1if0<= y <=1000andnot vis[y]:
vis[y] =True q.append((y, step +1))
return-1