You are locked inside a museum. To leave, you must collect every key and then reach the exit.
The museum is an by grid:
@: your starting position
$: the exit
.: empty floor
#: a wall
a–f: a key
A–F: a locked door
In one step you may move one cell up, down, left, or right. You cannot leave the grid or enter a wall. You may enter a locked door only if you hold its corresponding lowercase key.
Keys are collected automatically when you enter their cells. You keep them permanently; opening a door does not consume its key. A collected key’s cell remains traversable.
You may walk through the exit before collecting all keys, but you cannot leave until you have collected them all. Find the minimum number of steps needed to collect every key and reach the exit.
The first line contains and .
The next lines contain characters each, describing the grid.
Print the minimum number of steps, or -1 if escape is impossible.
There is exactly one @ and one $.
There are at most six keys, with no repeated key letter. There may be zero keys.
Every door has a corresponding key somewhere in the grid.
Multiple doors may use the same key.
Only the characters listed above occur.
In Sample 1, move down twice to collect a, return up twice, then move right six times through door A to the exit.
In Sample 2, door A blocks the only route to its own key.
In Sample 3, walk right twice to collect a, passing through the exit, then left once to leave.
| Sample Input 1 | Sample Output 1 |
|---|---|
3 7 @..A..$ .###.#. a...... |
10 |
| Sample Input 2 | Sample Output 2 |
|---|---|
1 4 @Aa$ |
-1 |
| Sample Input 3 | Sample Output 3 |
|---|---|
1 4 @$a. |
3 |