Cheese

Interview

Time limit1sMemory limit256 MB

Summary
In a grid maze, find the total shortest walking time for a mouse to eat cheeses of hardness 1 through N in order, each raising its strength by one.
Level

Medium4 of 10

Topics
BFS, Graph, Shortest path, Implementation
Solved
No attempts yet

Problem

This year, too, the cheese factories in JOI Town have started producing cheese, and a mouse has poked its head out of its nest. JOI Town is divided into a grid aligned with the four cardinal directions, and each cell is one of: a nest, a cheese factory, an obstacle, or an empty lot. The mouse starts from its nest, visits every cheese factory, and eats one piece of cheese at each.

There are NN cheese factories in this town, and each factory produces only one kind of cheese. The hardness of the cheese differs from factory to factory: for each hardness from 11 to NN, there is exactly one factory that produces cheese of that hardness.

The mouse's initial strength is 11, and every time it eats a piece of cheese its strength increases by 11. However, the mouse cannot eat cheese that is harder than its current strength.

The mouse can move to an adjacent cell in one of the four cardinal directions in 11 minute, but it cannot enter an obstacle cell. It may also pass through a cheese factory without eating its cheese. Write a program that computes the shortest time needed to finish eating all of the cheese. The time it takes the mouse to eat cheese is negligible.

Input

The input has H+1H+1 lines. The first line contains three integers HH, WW, NN (1≤H≤10001 \le H \le 1000, 1≤W≤10001 \le W \le 1000, 1≤N≤91 \le N \le 9) separated by spaces. Each of the following HH lines (lines 22 through H+1H+1) contains a string of WW characters made up of 'S', '1', '2', ..., '9', 'X', and '.', each representing the state of a cell. Let (i,j)(i, j) denote the cell that is ii-th from the north and jj-th from the west (1≤i≤H1 \le i \le H, 1≤j≤W1 \le j \le W). The jj-th character of line i+1i+1 is 'S' if cell (i,j)(i, j) is the nest, 'X' if it is an obstacle, '.' if it is an empty lot, and '1', '2', ..., '9' if it is a factory producing cheese of hardness 1,2,…,91, 2, \ldots, 9 respectively. The input contains exactly one nest and exactly one factory for each hardness 1,2,…,N1, 2, \ldots, N. Every other cell is guaranteed to be an obstacle or an empty lot. It is guaranteed that the mouse can eat all of the cheese.

Output

Output a single integer on one line: the shortest time (in minutes) needed to finish eating all of the cheese.

Examples3

  1. Example 1

    Input
    3 3 1
    S..
    ...
    ..1
    
    Expected output
    4
    
  2. Example 2

    Input
    4 5 2
    .X..1
    ....X
    .XX.S
    .2.X.
    
    Expected output
    12
    
  3. Example 3

    Input
    10 10 9
    .X...X.S.X
    6..5X..X1X
    ...XXXX..X
    X..9X...X.
    8.X2X..X3X
    ...XX.X4..
    XX....7X..
    X..X..XX..
    X...X.XX..
    ..X.......
    
    Expected output
    91