Treasure Hunt 2
InterviewTime limit1sMemory limit512 MB
Find the minimum fuel for a ship to reach the treasure on a grid, where moves to the three cells in the next column are free and all other moves cost 1.
- Level
Medium4 of 10
- Topics
- Graph, Shortest path, BFS, Matrix
- Solved
- No attempts yet
Problem
Geondeok succeeded in finding a treasure in the previous treasure hunt. Now he sails around the world as a member of a treasure expedition team.
Geondeok obtained a map of columns and rows showing the terrain of nearby islands. The map shows the surrounding sea, which is made of water and reefs. A ship cannot pass over reefs. The top-left cell of the map is , and the bottom-right cell is .
At each step, the ship moves to one of the 8 adjacent cells. The cells adjacent to are the where . For a safe voyage, the ship never leaves the map.
A current flows quickly from left to right across the sea on the map. Riding the current costs no fuel, but every other move costs 1 unit of fuel per cell. For example, if the ship is at , it can move to , , or without spending fuel. Moving to any other cell costs 1 fuel.
Input
The first line contains the height and the width of the treasure map. ()
The next lines contain the map. Each character is one of .#*K, meaning sea, reef, treasure, and ship. The ship and the treasure each appear exactly once.
Output
Print the minimum amount of fuel needed to reach the treasure while pushing through the current. If the treasure cannot be reached, print .