You are given an $n \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 $0$ or exactly $2$ walls.
Some plots carry a number ($0$, $1$, $2$, or $3$); 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 \times 5$ grid of plots:

one valid fence is:

The grid is always $n \times n$ with $1 \le n \le 6$, and each plot is either a number ($0$, $1$, $2$, or $3$) 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$ if no valid loop exists. A loop of length $0$ is invalid; a valid loop must enclose a non-zero area.
The input contains a series of fence puzzles. Each puzzle begins with a line containing $n$, the board dimension ($1 \le n \le 6$), followed by $n$ lines of $n$ 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 $0$.
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$ if the puzzle has no such loop. Print no extra whitespace beyond the newlines that separate the answers.