LC.P2059[转化数字的最小运算数]

方法一:BFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int minimumOperations(int[] nums, int start, int goal) {
Deque<Integer> queue = new ArrayDeque<>();
Map<Integer, Integer> map = new HashMap<>();
queue.offer(start);
map.put(start, 0);
while (!queue.isEmpty()) {
int cur = queue.poll();
int step = map.get(cur);
for (int num : nums) {
int[] result = new int[]{cur + num, cur - num, cur ^ num};
for (int x : result) {
if (x == goal) return step + 1;
if (x < 0 || x > 1000) continue;
if (map.containsKey(x)) continue;
map.put(x, step + 1);
queue.offer(x);
}
}
}
return -1;
}
}