Elegant Diamond
Time limit5sMemory limit512 MB
Embed the given digit diamond into a larger diamond symmetric about both axes with the fewest added digits.
- Level
Medium6 of 10
- Topics
- Brute force, Implementation, Simulation
- Solved
- No attempts yet
Problem
The king wants an elegant diamond and has hired you to make one. An elegant diamond is a two dimensional figure built from digits that is symmetric about a horizontal axis and about a vertical axis. Each of these four figures is an elegant diamond.
2
3 3
4 1 4
3 3
2
8
8 8
8
3
2 2
3
7
Each of these three figures is a diamond, but it is not elegant.
2
1 1
1
1
1 2
1 1 1
2 1
1
3
1 1
3 1 3
1 1
2
None of these three figures is a diamond.
1
1 1
2
222
2
8 8
0
00000
The king gives you a diamond that may not be elegant. You make it elegant by enhancing it: you add digits so that it grows into a bigger diamond. You do not want to spend much, so the cost has to be as small as possible.
Definitions
A diamond of size is lines of digits from 0 to 9, separated by single spaces, laid out this way:
- Line with has spaces, then digits separated by single spaces.
- Line with has spaces, then digits separated by single spaces.
An elegant diamond of size is a diamond of size with both of these symmetry properties:
- Horizontal symmetry: let be the number of digits on line . The -th digit on line (where is the first digit) equals the -th digit on line .
- Vertical symmetry: the -th digit on line (where is the first line) equals the -th digit on line .
A diamond of size can be enhanced by adding digits to it. The result of enhancing a diamond of size has these properties:
- The result is a diamond of size at least .
- The original diamond is part of the result. That is, there are values and such that for every and where the -th character of line of the original is a digit (not a space), the -th character of line of the result is also a digit and it is the same digit.
The cost of enhancing a diamond is the number of digits in the result of the enhancement minus the number of digits in the original diamond.
Input
The first line of the input gives the number of test cases . test cases follow. Each test case consists of a single integer on a line of its own, followed by a diamond of size .
Limits
Output
For each test case, print one line containing Case #x: y, where is the test case number starting from 1 and is the minimum cost of enhancing the given diamond into an elegant diamond. If the diamond is already elegant, is 0.
Note
The sample holds four cases. The diamonds of the first two cases are already elegant, so the cost is 0.
The third diamond can be enhanced into
3
1 1
1 2 1
1 1
3
Several enhancements are possible, and this one has the lowest cost, 5.
The fourth diamond can be enhanced into
9
1 1
6 3 6
9 5 5 9
6 3 6
1 1
9
for a cost of 7.