Cheese
InterviewTime limit1sMemory limit256 MB
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 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 to , there is exactly one factory that produces cheese of that hardness.
The mouse's initial strength is , and every time it eats a piece of cheese its strength increases by . 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 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 lines. The first line contains three integers , , (, , ) separated by spaces. Each of the following lines (lines through ) contains a string of characters made up of 'S', '1', '2', ..., '9', 'X', and '.', each representing the state of a cell. Let denote the cell that is -th from the north and -th from the west (, ). The -th character of line is 'S' if cell 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 respectively. The input contains exactly one nest and exactly one factory for each hardness . 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.