Another Brick in the Wall

Time limit1sMemory limit128 MB

Summary
Given a grid of bricks, each labeled by a letter, remove the fewest bricks so the removed cells form a connected top-to-bottom gap.
Level

Medium6 of 10

Topics
Graph, Shortest path, Implementation
Solved
No attempts yet

Problem

After years as a brick-layer, you have been called upon to analyze the structural integrity of various brick walls built by the Tetrad Corporation. Instead of using regular-sized bricks, the Tetrad Corporation seems overly fond of bricks made out of strange shapes.

A wall is a grid of unit cells, and every cell belongs to exactly one brick. The structural integrity of a wall can be approximated by the fewest number of bricks that must be removed to create a gap running from the top of the wall to the bottom. Removing a brick removes all of the cells it occupies, and those cells become part of the gap. Determine that minimum number for various odd walls created by Tetrad.

Input

The first line contains a single integer XX (1≤X≤1001 \le X \le 100), the number of data sets. Each data set consists of two parts:

  • A line M N (1≤M,N≤201 \le M, N \le 20), where MM and NN are the height and width (in cells) of the wall, respectively.
  • MM lines that follow, each exactly NN uppercase letters long. Each letter indicates which brick that cell belongs to. Every brick is contiguous: each cell of a brick is adjacent (up, down, left, or right; diagonals do not count) to another cell of the same brick. Different bricks may reuse the same letter, but two bricks that use the same letter are never adjacent to each other.

Output

For each data set, output on its own line the fewest number of bricks that must be removed to create a gap leading from some cell in the top row of the wall to some cell in the bottom row. Bricks stay fixed in place and do not fall when bricks beneath them are removed. A gap is a set of removed cells that is connected: each cell of the gap must be adjacent (diagonals do not count) to another cell of the gap.

Examples1

  1. Example 1

    Input
    3
    5 7
    AABBCCD
    EFFGGHH
    IIJJKKL
    MNNOOPP
    QQRRSST
    5 7
    AABBCCD
    AFFBGGD
    IIJBKKD
    MNNOOPD
    QQRRSST
    6 7
    ABCDEAB
    ABCFEAB
    AEAABAB
    ACDAEEB
    FFGAHIJ
    KLMANOP
    
    Expected output
    5
    2
    2