-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMinimumOperationsToConvertNumber.java
45 lines (44 loc) · 1.56 KB
/
MinimumOperationsToConvertNumber.java
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
/*https://leetcode.com/problems/minimum-operations-to-convert-number/*/
class Solution {
public int minimumOperations(int[] nums, int start, int goal) {
Set<Integer> set = new HashSet<Integer>();
set.add(start);
int steps = 0;
boolean[] visited = new boolean[1001];
visited[start] = true;
while (!set.isEmpty())
{
Set<Integer> adjSet = new HashSet<Integer>();
for (Integer node : set)
{
for (int num : nums)
{
int adjNode = node+num;
if (adjNode == goal) return steps+1;
if (adjNode >= 0 && adjNode <= 1000 && !visited[adjNode])
{
adjSet.add(adjNode);
visited[adjNode] = true;
}
adjNode = node-num;
if (adjNode == goal) return steps+1;
if (adjNode >= 0 && adjNode <= 1000 && !visited[adjNode])
{
adjSet.add(adjNode);
visited[adjNode] = true;
}
adjNode = node^num;
if (adjNode == goal) return steps+1;
if (adjNode >= 0 && adjNode <= 1000 && !visited[adjNode])
{
adjSet.add(adjNode);
visited[adjNode] = true;
}
}
}
set = adjSet;
++steps;
}
return -1;
}
}