Under construction

Still being built. Things may change

Gem Match Cascade

Time limit5sMemory limit512 MB

Summary
Try every adjacent swap on the gem board, simulate the match and fall cascade, and report the largest number of cleared gems.
Level

Medium5 of 10

Topics
Simulation, Brute force, Matrix
Solved
No attempts yet

Problem

John plays a gem matching game a lot, and his scores are stuck. Write a program that finds the move clearing the most gems.

The board is a grid of colored gems, like this one:

BGR
GRR
BGY

A move swaps two gems that touch horizontally or vertically. Swapping the first two gems of the second row changes the board to this:

BGR
RGR
BGY

Whenever three or more gems of the same color end up in a row or a column, all of them vanish at once. In this example the three green gems vanish.

B.R
R.R
B.Y

One move can build several groups at once. Take this board:

RGOY
RGOG
OOYO
RGOG
YBOB

Swapping the rightmost orange gem of the middle row with the yellow gem next to it

RGOY
RGOG
OOOY
RGOG
YBOB

builds a row of three and a column of five, and all of them vanish.

RG.Y
RG.G
...Y
RG.G
YB.B

Every gem sitting above an empty cell then falls until no empty cell is left below it.

...Y
RG.G
RG.Y
RG.G
YB.B

Rows or columns of three or more that appear after the fall vanish as well.

...Y
...G
...Y
...G
YB.B

This repeats until no row and no column holds three or more gems of the same color. The whole process is:

  • Swap two touching gems.
  • While some row or column holds three or more gems of the same color:
    • Remove those gems.
    • Drop gems until no gem sits above an empty cell.

In the real game, new gems drop in from the top to refill the board. Ignore that here.

Input

The first line holds the number of test cases TT. Each test case starts with a line holding two integers NN and MM separated by one space. The next NN lines each hold exactly MM uppercase letters, one letter per gem. Equal letters mean equal colors.

Limits

  • Every gem character is an uppercase letter.
  • The input board holds no row and no column with three or more consecutive gems of the same color.
  • 1≤T≤1001 \le T \le 100
  • 1≤N≤501 \le N \le 50
  • 1≤M≤501 \le M \le 50

Output

For each test case, print one line of the form Case #C: D, where CC is the test case number starting from 1 and DD is the largest number of gems a single swap can remove. If no two gems can be swapped, DD is 0.

Examples2

  1. Example 1

    Input
    3
    3 3
    BGR
    GRR
    BGY
    5 4
    RGOY
    RGOG
    OOYO
    RGOG
    YBOB
    3 3
    ABC
    DEF
    GHI
    
    Expected output
    Case #1: 3
    Case #2: 13
    Case #3: 0
    
  2. Example 2

    Input
    3
    1 5
    AABAA
    5 1
    A
    A
    B
    A
    A
    2 2
    AB
    BA
    
    Expected output
    Case #1: 3
    Case #2: 3
    Case #3: 0