Under construction

Still being built. Things may change

Building Zombie Fences

Time limit1sMemory limit128 MB

Summary
On an n x n grid with n at most 6, find the longest single closed fence loop using lattice-point walls so every numbered plot has exactly that many of its four sides walled.
Level

Medium7 of 10

Topics
Backtracking, Brute force, Graph, Implementation
Solved
No attempts yet

Problem

You are given an n×nn \times n grid of land plots. Build fences (walls) along the grid lines that join lattice points so the walls form a single closed loop — one simple cycle with no crossings and no branches. Equivalently, every lattice point must be touched by either 00 or exactly 22 walls.

Some plots carry a number (00, 11, 22, or 33); such a plot must be surrounded by exactly that many walls on its four sides. A plot with no number imposes no constraint.

For example, given the following 5×55 \times 5 grid of plots:

one valid fence is:

The grid is always n×nn \times n with 1≤n≤61 \le n \le 6, and each plot is either a number (00, 11, 22, or 33) or blank. Output the length of the longest possible loop that respects every numbered plot — equivalently, the number of lattice points on the loop — or −1-1 if no valid loop exists. A loop of length 00 is invalid; a valid loop must enclose a non-zero area.

Input

The input contains a series of fence puzzles. Each puzzle begins with a line containing nn, the board dimension (1≤n≤61 \le n \le 6), followed by nn lines of nn characters describing the grid. Each character is a digit 0–3 giving that plot's required wall count, or - for a plot with no constraint. A blank line follows each puzzle. The end of the input is marked by a line containing a single 00.

Output

For each puzzle, print on its own line the length of the longest fence loop that can be built while respecting every constraint, or −1-1 if the puzzle has no such loop. Print no extra whitespace beyond the newlines that separate the answers.

Examples2

  1. Example 1

    Input
    2
    22
    22
    
    3
    222
    222
    222
    
    5
    ----0
    2---2
    3--2-
    2-2--
    22---
    
    6
    222222
    2-22-2
    22222-
    22-2-2
    2-22-2
    222222
    
    0
    
    Expected output
    8
    -1
    32
    46
    
  2. Example 2

    Input
    2
    --
    --
    
    0
    
    Expected output
    8