Spiral
Time limit5sMemory limit128 MB
On an N by N grid with blocked fountain cells, find the longest path made of four straight segments turning only right, never revisiting a field.
- Level
Medium7 of 10
- Topics
- Brute force, Implementation, Prefix sum, Geometry
- Solved
- No attempts yet
Problem
Kalemegdan Park is the largest park in Belgrade. Model the park as an grid of unit fields. Some fields contain a fountain; every other field is empty. A rider may move between two empty fields only when they share an edge (up, down, left, or right).
The rider only likes spiral routes. A spiral route is built as follows: choose a starting empty field and a starting direction (North, East, South, or West). Move at least one field in that direction, then turn 90 degrees to the right; move at least one field in the new direction, and turn 90 degrees to the right again; move at least one field, and after a final 90 degree right turn move at least one more field. A route therefore consists of exactly four straight segments, and every turn is clockwise.
The route may never pass through a fountain and may never visit the same field twice. The length of a spiral route is the number of fields it covers (equivalently, one plus the total number of steps taken).

The figure above shows a park with (black squares are fountains) together with a few possible spiral routes.
Print the length of the longest spiral route the rider can take.
Input
The first line contains two integers and : the side length of the square park and the number of fountains.
Each of the next lines contains two integers and , the coordinates of one fountain. Field lies in row counted from the top and column counted from the left, so is the top-left field and is the bottom-left field. North means up, East means right, South means down, and West means left.
Output
Print a single integer: the length of the longest spiral route. At least one spiral route is guaranteed to exist.