Under construction

Still being built. Things may change

Chuck's Challenge

Time limit1sMemory limit512 MB

Summary
Find the fewest doors that must be opened to walk from the entrance to the exit of a grid maze, where keys unlock doors and unstable floors collapse after the player leaves them.
Level

Medium6 of 10

Topics
BFS, Bit manipulation, Graph, Simulation
Solved
No attempts yet

Problem

Chuck's Challenge is a game in which a player navigates a maze made of tiles in a grid. The player may find doors that can be unlocked with keys collected along the way. Write a program that determines the minimum number of doors that must be opened to reach the exit of the maze.

TileMeaningPassable
>EntranceYes
<ExitYes
a-zKeyYes
A-ZDoorSee rules
.GroundYes
+WallNo
~Unstable floorSee rules

Rules

  • Tiles that are diagonal to each other are not adjacent. Only up, down, left, and right count.
  • The player begins the maze on the entrance tile.
  • The player may only visit passable tiles that are adjacent to the tile the player is currently visiting.
  • A door stays impassable until the player has visited a tile with the matching key ('A' matches 'a', 'B' matches 'b', and so on).
  • At first, unstable floors are passable. If the player leaves an unstable floor and visits any other type of tile, that floor becomes impassable.
  • When an unstable floor becomes impassable, all adjacent unstable floors become impassable too.
  • The outer edge of the maze is an impassable wall.

Input

The first line contains the number of test cases TT (1≤T≤501 \le T \le 50). Each test case begins with a line containing two integers RR and CC (4≤R,C≤504 \le R, C \le 50). The next RR lines each contain a row of CC characters describing the maze. Only the characters listed in the table above appear in the maze.

Output

For each test case, print one line containing the minimum number of doors that must be opened to reach the exit. If the exit cannot be reached, print "Impossible".

Examples1

  1. Example 1

    Input
    2
    8 15
    +++++++++++++++
    +>............+
    +...a...+~+~+B+
    +~+++++++~+~+.+
    +~++..b..C+~+.+
    +~++A++++++~+.+
    +....~~~~~~c+<+
    +++++++++++++++
    8 6
    ++++++
    +>.A<+
    +.++++
    +.+.a+
    +~~..+
    +~~..+
    +~~..+
    ++++++
    
    Expected output
    2
    Impossible