Under construction

Still being built. Things may change

Robot In A Room

Time limit1sMemory limit128 MB

Summary
Simulate a vacuum robot that moves, turns right at walls, and recharges at outlets to find when it reaches the spilled drink.
Level

Medium4 of 10

Topics
Simulation, Implementation, Matrix
Solved
No attempts yet

Problem

You just bought a robotic vacuum cleaner, and you like watching it explore your room. After a long look, you worked out the rules it follows.

  • Moving one cell takes one minute.
  • The battery holds dd units, so a full charge is worth dd moves.
  • Every move and every turn costs one minute and one unit of battery.
  • When the cell straight ahead is a wall or an obstacle, the robot turns right 90 degrees in place.
  • Outlets sit in the walls, so the robot cannot enter an outlet cell. It charges only from a cell that touches an outlet horizontally or vertically, never diagonally.
  • The robot checks its battery after every one-minute action (a move or a turn). If the remaining battery bb satisfies 2b≤d2b \le d and the current cell touches an outlet, the robot stops there and charges until full. Charging takes one minute per unit of battery added.
  • If the battery reaches 0 and the robot cannot charge, it stops for good.

You just spilled your drink on the carpet. The robot cleans the mess the moment it enters that cell, and cleaning costs no time and no battery. Given the robot's starting position and the position of your spill, find how many minutes the robot needs to reach the mess.

Input

The first line holds the number of test cases TT (1≤T≤5001 \le T \le 500).

The first line of each test case holds two integers nn and dd separated by a space. The room is an n×nn \times n grid of unit squares, and dd is the number of moves a fully charged robot can make (5≤n≤205 \le n \le 20, 15≤d≤3015 \le d \le 30).

The next nn lines each hold nn characters.

CharacterMeaning
-open space
xan obstacle such as a wall or a chair
myour mess
rthe robot's starting position. It always starts facing right with a full battery, and it never starts inside a wall.
pa power outlet

Each test case holds exactly one r and exactly one m.

Output

For each test case print one line in the form Case x: y, where xx is the test case number starting at 1 and yy is the number of minutes the robot needs to reach the mess. If the robot never reaches the mess, print NEVER in place of yy.

Examples1

  1. Example 1

    Input
    2
    5 10
    xxpxx
    x---x
    x-m-x
    xr--x
    xxxxx
    10 30
    xxxxxxxxxx
    x-x------x
    x--------x
    xr-xx----x
    x--xx----p
    xm-------x
    xx------xx
    xxxx-----x
    x--------x
    xxxxxxxxxx
    
    Expected output
    Case 1: NEVER
    Case 2: 51