All problems

Problem 938

Shortest Path to Get All Keys

Hard · 30 pts · Matrix, Breadth-First Search, Bit Manipulation

Problem

In a grid, '@' is the start, '#' a wall, '.' an empty cell, lowercase letters are keys and uppercase letters are locks; lock A opens only with key a. You move one step up, down, left or right per move and pick up keys by walking onto them. Find the fewest moves needed to collect all keys, or -1. There are at most 6 keys, so run a breadth-first search over states (row, column, set of keys held as a bitmask).

Input

The first line contains R and C. Each of the next R lines is a row of the grid.

Output

Print the minimum number of moves, or -1.

Constraints

1 <= R, C <= 30; exactly one '@'; at most 6 keys, using the first letters a, b, c, ... with exactly one of each key and at most one of each lock

Example input

3 5
@.a..
###.#
b.A.B

Example output

8

Explanation

In @.a.. / ###.# / b.A.B, walk right to key a (2 moves), down through the gap and left past lock A (now open) to key b. The shortest such walk takes 8 moves.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum Cost to Make at Least One Valid Path in a Grid Next: Remove Max Number of Edges to Keep Graph Fully Traversable