Introduction
Graphs can be used to solve many problems in computer science. Graph problems include, for example, network analysis, route mapping, and scheduling. For studying and addressing graph problems, graph search techniques such as breadth-first search are helpful. BFS (breadth-first search) is a famous graph search technique that can be used to solve various problems, including finding the shortest path in a graph and solving puzzle games like Rubik's Cubes.
This blog will discuss one such problem, Minimum Operations to Convert Number, and solve it using BFS.
Problem Statement
You are given two integers, START and GOAL. You are also given a 0-indexed integer array NUMS with distinct integers.
If initially, an integer, X = START, and 0 <= X <= 1000, you can perform the following operations, for any index i in the array:
- X + NUMS[i] = A
- X - NUMS[i] = B
- X ^ NUMS[i] = C
Also, each NUMS[i] can be used in any order and any number of times.
The problem asks you to find the minimum number of operations to convert START into GOAL, and if this is not possible, return -1.
Let us try to understand this with the help of a few examples.
Example
- START = 2
GOAL = 12
NUMS = [2, 4, 12]
→ 2 + 12 = 14
14 - 2 = 12
So, minimum number of operations performed = 2
- START = 0
GOAL = 3
NUMS = [1]
→ 0 + 1 = 1
1 + 1 = 2
2 + 1 = 3
So, minimum number of operations performed = 3
- START = 0
GOAL = 1
NUMS = [2, 8, 16]
→ There’s no way to convert 0 to 1.
So, the answer is = -1
Approach
We will be using BFS to solve this problem. Our goal is to reach GOAL from START, and we are allowed to perform three types of operations.
Let’s suppose we use these operations on start and we get:
START + NUMS[i] = A
START - NUMS[i] = B
START ^ NUMS[i] = C
- Either A, B, or C is equal to GOAL.
- None of A, B, or C is equal, and we need to perform these operations until we reach GOAL. But this could result in a Time Limit Exceed, so to avoid this, we would maintain an array VISITED, which would keep a record of the values that have been calculated before. In this way, we would not have to perform repetitive calculations.