Building Zombie Fences
Time limit1sMemory limit128 MB
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 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 or exactly walls.
Some plots carry a number (, , , or ); 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 grid of plots:

one valid fence is:

The grid is always with , and each plot is either a number (, , , or ) 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 if no valid loop exists. A loop of length 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 , the board dimension (), followed by lines of 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 .
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 if the puzzle has no such loop. Print no extra whitespace beyond the newlines that separate the answers.