Treasure Hunt

Given a Matrix of characters A of size N x M. Matrix A contains ”.” which represents an empty cell, ”#” represents a wall, ”@” denotes the starting point,

(“a”, “b”, …) are keys, and (“A”, “B”, …) are locks.

We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions. We cannot walk outside the grid, or walk into a wall. If we walk over a key, we pick it up. We can’t walk over a lock unless we have the corresponding key.
For some 1 <= K <= 6, there is exactly one lowercase and one uppercase letter of the first K letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.

Return the lowest number of moves to acquire all keys. If it’s impossible, return -1.

Input Format

The first and only argument given is the character matrix A.

Output Format

Return the lowest number of moves to acquire all keys. If it's impossible, return -1.	


1 <= N, M <= 30
A[ i ][ j ] contains only '.', '#', '@', 'a'-'f' and 'A'-'F'
The number of keys is in [1, 6]. Each key has a different letter and opens exactly one lock.

For Example

Input 1:
    A = [ [@.a.#] , [###.#] , [b.A.B] ]

Output 1:

Input 2:
    A = [ [@..aA] , [..B#.] , [....b] ]

Output 2:
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Treasure Hunt on Interview Code Editor
Sign Up
to access hints and editorial solutions for Treasure Hunt


Click here to start solving coding interview questions