Cows on Ice
Time limit1sMemory limit128 MB
Bessie slides on ice until a rock stops her; find the minimum number of pushes to move from her start cell to the goal cell.
- Level
Medium7 of 10
- Topics
- BFS, Graph, Hash map, Simulation
- Solved
- No attempts yet
Problem
Bessie is ice skating on a large frozen lake modeled as a 2D grid whose coordinates range from to on both axes. () of the grid cells contain rocks, numbered through ; every other cell is slippery ice.
Bessie is a poor skater, so she can only move by pushing off from her current cell (which always sits next to a rock) and then sliding in a straight line until she slams into another rock, coming to rest in the cell immediately before that rock. She can push herself only straight north, east, south, or west, and she cannot push through a rock, so she usually has at most three useful directions.
A slide only works if some rock lies ahead of her in that direction to stop her; with no rock ahead she would slide forever, so every push must be aimed carefully.
For example, Bessie (B) wants to reach the goal (G) at , directly east of her (. = ice, * = rock, B = Bessie, G = goal). Sliding straight east would carry her past the goal, because she can only stop by hitting a rock. One way to reach is:
(a) (b) (c) (d)
4 .....*. .....*. .....*. .....*.
3 ..*.... slide ..*.... slide ..*.... slide ..*....
2 ......* north ..B...* east .....B* south ......*
1 .*B..G. ------> .*...G. ------> .*...G. ------> .*...B.
0 *....*. *....*. *....*. *....*.
0123456
In situation (a) she could try north, east, or south, but only the northward slide has a rock to stop her. In situation (b) only the eastward slide has a stopping rock.
Rock sits at with each coordinate between and , and no two rocks share a cell. Bessie starts at , always next to a rock, and her goal is ; every coordinate lies in the same range, and the goal is always reachable.
Sliding costs Bessie nothing, but pushing off a rock tires her out. Determine the minimum number of pushes she needs to reach the goal.
Input
- Line 1: five space-separated integers , , , , .
- Lines 2 through : line contains two space-separated integers and , the location of rock .
Output
- Line 1: a single integer, the minimum number of pushes Bessie needs to reach her goal.