Under construction

Still being built. Things may change

Kangaroo Commotion

Time limit7sMemory limit512 MB

Summary
Find the fewest jumps for a kangaroo to visit all k other kangaroos in order, then stop at the safe area, with jump velocity changing by at most 1 per step on a grid.
Level

Medium6 of 10

Topics
BFS, Bit manipulation, Matrix
Solved
No attempts yet

Problem

Bushfires are threatening your habitat. As a kangaroo, you must warn the other kangaroos in your troop as fast as possible and flee to a safe area.

You stand still at the start and jump to the other kangaroos' locations. You visit them in a specific order so that each one has enough time to escape. After visiting all of them, you keep jumping to the safe area and stop there.

Each jump moves you a possibly negative integer distance north and/or east. Your muscles are limited, so you can change your speed in each direction by at most 11 per jump. Formally, if jump ii moves you vx,iv_{x,i} north and vy,iv_{y,i} east, then jump i+1i+1 must satisfy ∣vx,i+1−vx,i∣≤1|v_{x,i+1} - v_{x,i}| \leq 1 and ∣vy,i+1−vy,i∣≤1|v_{y,i+1} - v_{y,i}| \leq 1.

Find the minimal number of jumps needed to go from your current position to the safe area via all other kangaroos, without leaving the grid. You must come to a full stop at the end, so the last jump must both start and end at the safe area.

Figure K.1 shows one possible way to reach the safe area in 9 jumps in Sample 1.

Input

The first line contains three integers rr, cc (1≤r,c≤501\leq r, c \leq 50), the number of rows and columns of the grid, and kk (1≤k≤51\leq k\leq 5), the number of other kangaroos you need to warn.

The next rr lines each contain cc characters. A . is an open space and a # is a bush where you cannot jump. Your start position is 0. The characters 1 to k mark the other kangaroos, in this order. The character k+1 marks the safe area where you should stop.

Output

If you can reach the safe area, output the minimal number of jumps needed. Otherwise, output impossible.

Examples4

  1. Example 1

    Input
    5 5 1
    0..2.
    .###.
    .....
    .....
    .#.#1
    
    Expected output
    9
    
  2. Example 2

    Input
    2 2 2
    03
    12
    
    Expected output
    4
    
  3. Example 3

    Input
    1 5 1
    .0#21
    
    Expected output
    8
    
  4. Example 4

    Input
    3 4 1
    #0##
    #.#2
    1###
    
    Expected output
    impossible