Market Board (Large)

Free dice land on uniform random faces and each cell scores by the longest run of two to four equal faces covering it; find the expected total.

Medium7ProbabilityCombinatoricsNo attempts yetTime limit5sMemory limit512 MB

Problem

While climbing Jirisan you stop at a market day. In one corner of the crowd somebody is running a game.

The game uses a grid board of NN rows and MM columns on a table. Every cell of the grid holds one KK-sided die.

The host fixes some of the dice so that a chosen face shows and leaves the rest loose. The board is then shaken, and every die that is not fixed, called a free die, comes to rest showing one of its KK faces. Each face shows with the same probability 1/K1/K, and the dice are independent of each other.

Once the board stops, every cell is scored. Four directions count: horizontal, vertical, and the two diagonals. A cell is scored like this.

  1. If some run of four consecutive cells in one direction contains this cell and all four show the same face, the cell scores S4S_4.
  2. Otherwise, if some run of three consecutive cells in one direction contains this cell and all three show the same face, the cell scores S3S_3.
  3. Otherwise, if some run of two consecutive cells in one direction contains this cell and both show the same face, the cell scores S2S_2.
  4. Otherwise the cell scores 0.

The score of the game is the sum of the scores of all cells.

The dice have been fixed and the board is about to be shaken. Compute the expected score of the game.

Input

The first line has the number of test cases TT.

The first line of each test case has six integers NN, MM, KK, S4S_4, S3S_3, S2S_2 separated by spaces. NN is the number of rows of the board, MM is the number of columns, and KK is the number of faces of a die. S4S_4, S3S_3 and S2S_2 are the scores described above.

The next NN lines give the rows of the board from the top row down. Each line is a string of length MM and gives the state of the dice in that row from the left. A fixed die is written as a single digit from 1 to KK, the number of the face it shows. A free die is written as a question mark ?.

Limits

  • 1T501 \le T \le 50
  • 2N1002 \le N \le 100, 2M1002 \le M \le 100
  • 2K92 \le K \le 9
  • 0S2S3S41000 \le S_2 \le S_3 \le S_4 \le 100
  • There is no limit on the number of free dice.

Output

For each test case print one line of the form Case #x: y, where xx is the test case number starting at 1 and yy is the expected score of that case. Round yy to seven digits after the decimal point and print exactly seven digits after the point.