G2. Grid Crash II
time limit per test
15 seconds
memory limit per test
1024 megabytes
input
standard input
output
standard output

Since getting his job at Iceberg Corporation, Rami has been ignoring his tasks and playing a new game called Grid Crash. It is a game played on a grid $$$G$$$ of size $$$n\times m.$$$ Each cell in the grid either has some colour, or is empty.

Initially, each cell $$$(i,j)$$$ in the grid contains some color $$$c_{i,j}.$$$ The grid itself contains at most 4 distinct colours.

Now the game is played as follows:

  • Rami selects some cell $$$(i,j)$$$ with color $$$c_{i,j}$$$ and removes the color.
  • This induces a chain reaction, on which adjacent cells of $$$(i,j)$$$ with the same color are also removed. Also, the adjacent cells of those that have color $$$c_{i,j}$$$ are removed, and so on.
  • After that, each non empty cell $$$(a-1,b)$$$ that is on top of an empty cell $$$(a,b)$$$ will swap their content. That is, $$$(a-1,b)$$$ will be empty, and $$$(a,b)$$$ will contain $$$c_{a-1,b}.$$$ This will be repeated until all empty cells will be on top of colorful cells.
  • After that, if we have a column $$$C_{i}$$$ of empty cells, then we swap its content with $$$C_{i+1}.$$$ This will be repeated until empty columns will be at the rightmost.
  • Rami will repeat step 1 until the grid has no remaining color.
To illustrate how the game works, we will show the following example of a move on a grid:

Now, Rami wants to finish the game in the fewest moves possible. Please help him.

Input
  1. The first line contains two integers $$$1\le n,m\le 5:$$$ The dimensions of the grid.
  2. The following $$$n$$$ lines contain each $$$m$$$ characters $$$c_{i,j} \in\{\mathtt{A},\dots,\mathtt{Z}\}:$$$ The $$$(i,j)^{\text{th}}$$$ cell of the grid.
Output

A single integer $$$r:$$$ the minimum number of moves to win the game.

Examples
Input
5 5
BWBBB
WWBWW
BWBWB
BWBBB
WWWWW
Output
3
Input
5 5
RRRRR
GGRBB
RRRRR
ARRRA
ARRRA
Output
4
Input
5 5
GGGGG
GRRRR
GGGGG
GRRRR
GGGGG
Output
2
Note

It is guaranteed that the grid does not contain more than 4 distinct colours.

The following example shows a sequence of moves that solves the first game (test case 1) in $$$3$$$ moves. It can be shown that it is optimal: