Skip to content

Commit 2a81a24

Browse files
Create minimum_operations_to_convert_number.cpp
1 parent 051cf05 commit 2a81a24

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
public:
3+
int minimumOperations(vector<int>& nums, int start, int goal) {
4+
int ans = 0;
5+
6+
vector<bool> visited(1001, false); //visited array
7+
queue<int>q;//queue for BFS
8+
9+
q.push(start); //add start in queue as base for BFS
10+
11+
while (!q.empty())
12+
{
13+
int size = q.size();
14+
while (size--)
15+
{
16+
int x = q.front();
17+
q.pop();
18+
19+
if (x == goal) //x == goal return ans
20+
{
21+
return ans;
22+
}
23+
else if (x > 1000 || x < 0 || visited[x]) //x out of bound [0,1000] or x is previously visited //no need to again proceed it
24+
{
25+
continue;
26+
}
27+
28+
//so now x is un visited
29+
for (auto i : nums) //do all three operation(+,-,^) on x and add that value in queue
30+
{
31+
q.push(x + i);
32+
q.push(x - i);
33+
q.push(x ^ i);
34+
}
35+
visited[x] = true; //mark x as visited
36+
}
37+
ans++; //operation count increase by 1
38+
}
39+
return -1; //not fount goal in above BFS so return -1
40+
}
41+
};

0 commit comments

Comments
 (0)