import argparse
from collections import deque
from itertools import groupby


def make_grid(n):
    clamp = [min(n - 3, max(4, i)) for i in range(1, n + 1)]
    return [''.join('#' if (j - 2*i - 2) % 5 == 0 else '.' for j in clamp) for i in clamp]


def count_words(lines):
    lengths = [sum(1 for _ in run) for line in lines for color, run in groupby(line) if color == '.']
    assert lengths and min(lengths) >= 4
    return len(lengths)


def check_grid(grid):
    n = len(grid)
    assert all(len(row) == n and set(row) <= {'.', '#'} for row in grid)
    assert grid == [row[::-1] for row in reversed(grid)]
    white = {(i, j) for i, row in enumerate(grid) for j, color in enumerate(row) if color == '.'}
    root = next(iter(white))
    seen, queue = {root}, deque([root])
    while queue:
        i, j = queue.popleft()
        for neighbor in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
            if neighbor in white and neighbor not in seen:
                seen.add(neighbor)
                queue.append(neighbor)
    assert seen == white
    return count_words(grid), count_words(zip(*grid))


def max_line(n, start_weight, black_weights):
    states = {0: 0}
    for i in range(n):
        following = {}
        for width, value in states.items():
            choices = [(min(4, width + 1), value + (start_weight if width == 0 else 0))]
            if width in (0, 4):
                choices.append((0, value + black_weights[i]))
            for state, candidate in choices:
                following[state] = max(candidate, following.get(state, candidate))
        states = following
    return max(states[0], states[4])


def check_bounds(n):
    m = n // 5
    a = {1, 2, n-1, n}
    c = {position for k in range(1, m) for position in (5*k, 5*k+1)}
    b = set(range(1, n+1)) - a - c
    wa = max_line(n, 1, [0]*n)
    wb = max_line(n, m-1, [-int(i in c) for i in range(1, n+1)])
    wc = max_line(n, m-1, [int(i in b) for i in range(1, n+1)])
    assert wa <= m and wb <= (m-1)**2 and wc <= m*(m-1)+1
    numerator = 2*(len(a)*wa*(m-1) + len(b)*wb + len(c)*wc)
    limit, remainder = divmod(numerator, m-1)
    assert remainder == 0
    return limit


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('sizes', type=int, nargs='*', default=[35])
    parser.add_argument('--grid', action='store_true')
    args = parser.parse_args()
    for n in args.sizes:
        if n < 15 or n % 5:
            parser.error('Each size must be a multiple of 5 and at least 15.')
        grid = make_grid(n)
        across, down = check_grid(grid)
        upper = check_bounds(n)
        assert across + down == upper == 2*(n*n - 3*n + 20)//5
        print(f'{n} by {n}: {across} across, {down} down, verified upper bound {upper}')
        if args.grid:
            print('\n'.join(grid))
