eolymp
bolt
Try our new interface for solving problems
Problems

Containing Zombies and Respecting Building Codes

Containing Zombies and Respecting Building Codes

It's well documented that the only way to thwart zombies is to trap them in closed fences. Zombie hunters have for years been luring zombies into clear spaces and then erecting such fences at lightning speeds so they can't go very far. Unfortunately, government has its zoning laws, its taxes, and its building codes, and recently they started to enforce silly constraints on how these zombie-enclosing fences can be constructed. According to city codes, fence posts must be planted at regular intervals, and the fences themselves must respect arbitrary limits on how many walls can surround a unit square of land. We also want to build as long of an enclosing fence as possible, because the government has plenty of money to waste on such things. \textbf{Building Zombie Fences} × Build walls between vertices to form a single enclosed fence without crossings or branches. The number indicates exactly how many walls - according to the crazy city building laws - must surround it (and a lack of number means there's no constraint.) So, presented with the following \textbf{55} grid of land squares: \includegraphics{https://static.e-olymp.com/content/1a/1a151fa09ce072560382c8c84782c6b881c57213.jpg} the following fence could be constructed: \includegraphics{https://static.e-olymp.com/content/54/549eb6524dd0199a8e9f080e1a12634244910914.jpg} -1 The grid of lots is always \textbf{n}×\textbf{n} (\textbf{1} ≤ \textbf{n} ≤ \textbf{6}), and each lot is either a number (\textbf{0}, \textbf{1}, \textbf{2}, or \textbf{3}) to impose a constraint, or a blank if no constraint is being imposed. You're to output the length of the longest possible loop (or equivalently, the number of vertices in the loop), or '' if no loop exists. Note that loops of length \textbf{0} are invalid. A valid loop must enclose a non-zero amount of area. \InputFile - The input is a series of zombie fencing problems, expressed by \textit{n}, the dimension of the problem, followed by an \textbf{n}×\textbf{n} grid (\textbf{1} ≤ \textbf{n} ≤ \textbf{6}) with the number constraints (with the '' to represent no constraint), followed by a blank line. End of input is marked by a single '\textbf{0}'. \OutputFile For each fence problem, you should print the length of the longest fence loop that can be constructed for that problem while still respecting all constraints, or you should print '\textbf{-1}' if the problem has no such solution. There should be no extraneous white space, save for the newlines that separate each of the fence lengths.
Time limit 1 second
Memory limit 64 MiB
Input example #1
2
22
22

3
222
222
222

5
----0
2---2
3--2-
2-2--

6
222222
2-22-2
22222-
22-2-2
2-22-2
222222

0
Output example #1
8
-1
32
46
Source ACM ICPC North America - Pacific Northwest 2010