Stack Maze
Time limit8sMemory limit256 MB
You move only right or down through the grid, pick up lettered jewels, and drop them into matching holes in last-in-first-out order for the most matches.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Stack, Graph
- Solved
- No attempts yet
Problem
The maze is a grid cells wide and cells tall. The upper left cell is and the lower right cell is . You start at and have to reach , and you can only move one cell to the right or one cell down.
Here is an example of a maze.
...#......
a###.#####
.bc...A...
##.#C#d#.#
.#B#.#.###
.#...#e.D.
.#A..###.#
..e.c#..E.
####d###.#
#....#.#.#
##E...d.C.
Some cells are free (.) and some are blocked by a rock (#), which you cannot enter. Some free cells hold a jewel (a lowercase letter) and some hold a hole for a jewel (an uppercase letter). Different letters mean different types of jewel, so a cell marked a holds a jewel of type A and a cell marked A holds a hole for a jewel of type A. Placing a jewel into a hole of its own type makes something happy happen.
On a cell with a jewel you choose whether to pick the jewel up. On a cell with a hole you choose whether to place a jewel you carry. You start with no jewels. Your bag is very large, so you can carry any number of jewels. The bag is a stack, so you can only take out the jewel you picked up last.
On the way from to , how many jewels can you place into holes of the matching type?
Input
The input holds a sequence of datasets. A line with two zeros ends the input, and that line is not a dataset.
Each dataset has this format.
H W
C11C12...C1W
C21C22...C2W
...
CH1CH2...CHW
and are the height and the width of the grid, and . Each of the next lines holds characters with no spaces between them. The -th character of the -th line gives the type of the cell in row and column as described above. The starting cell (row 1, column 1) and the destination cell (row , column ) are never #.
Within one dataset, each lowercase letter and each uppercase letter appears at most 10 times.
Output
For each dataset, print on one line the maximum number of jewels you can place into holes of the matching type. Print -1 if you cannot reach the cell .