Deadly Rain
Time limit1.5sMemory limit1024 MB
Find the fewest moves from S to E on an N by N grid while managing umbrellas with durability and health, where rain hits every cell except S and E.
- Level
Hard8 of 10
- Topics
- BFS, Bit manipulation, Graph
- Solved
- No attempts yet
Problem
A square grid has sides of length . Death rain falls on every cell except two: your current position and the safe zone. Rain is also about to fall on your current position, so you must cross the death rain and reach the safe zone quickly.
The grid contains umbrellas that block the rain for a while. Each umbrella has durability , and all umbrellas have the same durability. When you are rained on while holding an umbrella, its durability drops by 1. The umbrella disappears when its durability reaches 0.
Each move proceeds in this order:
- Move up, down, left, or right. You cannot move outside the grid.
- If you moved onto the safe zone, stop.
- If you moved onto a cell with an umbrella, pick it up. If you already hold an umbrella, discard it and take the new one. A discarded umbrella can no longer be used.
- If you are rained on, durability drops by 1 when you hold an umbrella. Otherwise, your health drops by 1.
- If the umbrella's durability reaches 0, it disappears.
- If your health reaches 0, you die.
- If you still have health, repeat the steps above until you reach the safe zone.
Find the minimum number of moves needed to reach the safe zone from your current position.
Input
The first line contains , your current health , and the umbrella durability , separated by spaces.
The next lines each contain one row of the grid as a string of characters. U marks an umbrella, S marks your current position, E marks the safe zone, and . marks an empty cell. There is exactly one S and exactly one E.
Output
Print the minimum number of moves needed to reach the safe zone. If you cannot reach the safe zone, print -1.
Constraints
All given numbers are integers.