


You are given ‘GRID’= [[“@.aA”],[“.B#.”],[“...b”]]. Then the answer will be 5.

The first line of the input contains a single integer 'T', representing the number of test cases.
The first line of each test case contains an integer ‘N’, representing the number of rows in ‘GRID’.
The next ‘N’ lines contains a String, representing a row of the ‘GRID’.
For each test case, print the minimum number of moves to get all the keys. Print -1 if it is impossible to get all keys.
Print the output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 100
1 <= M <= 100
GRID[i][j] is either an English letter, ‘.’, ‘#’, or ‘@’.
Each key is unique.
Each key has a matching lock.
Alphabets for the keys and locks are chosen in the same order as English alphabets.
The number of keys is in the range [1, 6].
Time Limit: 1 sec
Prerequisite: Breadth-First Search, Dp & Bit-masking
In this approach, we will use BFS to get the shortest path to get all the keys. We will start from the starting position and move in all four cardinal directions. We use a queue to perform BFS. The BFS queue will store the next possible states for any state. Each time we move to the next state, we will increment the number of moves. When we have collected all the keys, we will stop our BFS and return the number of moves. To prevent revisiting any state, we will use a 3d array to track visited states.
What is the state?
A state has three fields (x, y, key). (x, y) are the coordinates of a cell in the grid, and key is the number of keys we have in this state.
How to confirm if all keys are collected?
To confirm if all the keys are collected, we use the concept of DP & Bit-masking. As the alphabets are chosen in the same order as the English alphabets, we will have a variable ‘MAX’ with us, which will help us to check if we have collected all keys or not. For example, if the max alphabet is ‘c’, our max will be 4. We will represent each alphabet as a bit in the integer keys. We get ‘c’, ‘MAX’ is 100. When we get ‘a’, ‘MAX’ becomes 101. When we get ‘b’, ‘MAX’ becomes 111. Now, if the number of keys of the current state is equal to ((1<<max)-1), then it means we have collected all the keys.
Algorithm :