Mine Layer (Large)

Given a Minesweeper-style grid of neighbor counts, find the maximum number of mines the middle row can hold in any layout that matches all counts.

Medium7Dynamic programmingImplementationBrute forceNo attempts yetTime limit5sMemory limit512 MB

Problem

Mine Layer is a puzzle much like Minesweeper. The board is an R×CR \times C grid, and every square either holds one mine or holds none.

The puzzle is given as a grid of numbers. Each number counts the mines in that square itself together with the squares next to it in all eight directions. Squares outside the board are not counted, so the numbers run from 0 to 9.

The goal is to find a mine layout that matches every given number.

The picture below shows a 3×43 \times 4 grid. The original layout is on the left, and the puzzle built from it is on the right.

A puzzle can have several layouts, so print the largest number of mines the middle row can hold. The number of rows RR is always odd, so the middle row is row (R+1)/2(R+1)/2 counted from the top, and at least one layout always matches the numbers.

Input

The first line contains the number of test cases NN. NN test cases follow.

The first line of each test case contains the number of rows RR and the number of columns CC, separated by a space. RR is always odd. Each of the next RR lines contains the CC numbers of that row, separated by spaces.

Limits

  • 1N501 \le N \le 50
  • Every puzzle has at least one matching layout.
  • RR is an odd number between 3 and 49, inclusive.
  • 3C493 \le C \le 49

Output

For each test case, print one line in the form Case #X: Y, where XX is the 1-based test case number and YY is the largest number of mines the middle row can hold in a layout that matches every given number.