Singapore Tour
Time limit2sMemory limit512 MB
Start at C, collect values from up to 14 grid spots with per-step cost 2, and return for the maximum net score.
- Level
Medium6 of 10
- Topics
- Dynamic programming, BFS, Graph
- Solved
- No attempts yet
Problem
A tourist has a map of Singapore drawn as an grid with . Every cell is one of the following.
~(tilde) is water..is land.- A digit from
2to9is an attractive spot. Cis Changi Airport.
The map below is a grid with one C and two attractive spots labeled 5 and 6.
~.~.~
6.~5.
~..C~
There are attractive spots with . The digit written on spot is its satisfaction value with , so a spot labeled 5 has . The tourist gains points when he visits spot .
The tourist moves one cell at a time in the four directions (north, east, south, west) and never enters a water cell. Every cell that is not water is passable, whether it is land, an attractive spot, or Changi Airport. Singapore is a well built city, so from any non-water cell the tourist reaches every other non-water cell. Walking is tiring, so each step costs satisfaction points. Rows and columns are numbered from 0. On the map above, walking from the C at row 2, column 3 to the 6 at row 1, column 0 along a shortest path takes four steps and costs points.
The tourist lands at Changi C, tours the spots he wants, and returns to C to fly home. He may cross any non-water cell as many times as he likes, but he collects the satisfaction of each spot only once. Given the map, what is the largest total satisfaction he can reach?
On the map above, the tour C → 6 → 5 → C gives points. The tour C → 5 → C gives point, and that is the largest value over all tours. The tourist skips 6 because it is not worth the walk.
Input
The first line contains the integers and separated by one space. Each of the next lines contains exactly characters. The input holds exactly one C and between 0 and 14 attractive spots.
Output
Print one integer, the largest total satisfaction the tourist can reach. He may visit no spot at all, so the answer is never negative.