Source: EGMO-2025-P5
Category: Operations and Strategies

Problem: "Given an integer $n>1$. An $n\\times n$ chessboard is called a direction diagram if each of its $n^2$ squares contains an arrow pointing to one of the four directions: up, down, left, or right. For an initial direction diagram, a turbo snail starts moving from a certain square on the chessboard. In each move, the snail advances one square in the direction of the arrow in its current square (it may move off the board). After each move, all arrows on the chessboard rotate $90^\\circ$ counterclockwise simultaneously. A square is called good if, starting from this square and moving according to the above rules, the snail passes through each square of the chessboard exactly once, never moves off the board, and finally returns to the initial square. For a given $n$, determine the maximum number of good squares over all possible initial direction diagrams.
"

Answer: It is $0$ when $n$ is odd, and $\\frac{n^2}{4}$ when $n$ is even.

Reference solution:
The maximum number of good squares is $0$ when $n$ is odd, and $\frac{n^2}{4}$ when $n$ is even.

For odd $n$, coloring the board black and white demonstrates that the snail moves between cells of alternating colors on each turn. Since the total number of cells is odd, a Hamiltonian cycle cannot exist, yielding exactly $0$ good cells.

For even $n$, choosing a Hamiltonian cycle and setting the initial arrow directions accordingly allows the starting cell to be good. Along this cycle, exactly one in every four consecutive cells is a good cell, because the arrow direction aligns with the required path only every four moves due to the simultaneous $90^\circ$ rotations. This establishes a lower bound of $\frac{n^2}{4}$ good cells.

At the top-left corner of the board, there are exactly four valid local configurations for the sequence of moves entering and exiting the corner cell. Because one cannot obtain another configuration by simultaneously rotating the three arrows involved in a given configuration, any fixed initial arrow diagram uniquely determines how a Hamiltonian cycle passes through the top-left corner. This uniquely dictates the subsequent route along the arrow directions, meaning there is only one valid Hamiltonian cycle. Since the number of moves from any good cell to the top-left corner must be congruent modulo $4$, the number of good cells is exactly $\frac{n^2}{4}$.

Grading guidelines:
(Partial) 1. For odd n, used a correct parity/colouring argument (e.g. checkerboard colouring) to show the snail alternates colours each move and hence a Hamiltonian cycle visiting all n^2 cells is impossible, concluding there are no good squares. 2. For even n, gave a valid construction from a Hamiltonian cycle: defined initial arrows so that starting from some chosen cell the snail follows the cycle while arrows rotate, producing at least one good square (or a positive proportion of them). 3. Established the key “mod 4” alignment fact: along any fixed cycle, a starting square is good only when the local required direction matches the current arrow orientation, which occurs with period 4, implying at most one in every four consecutive vertices on the cycle can be good. (Almost) 1. Correctly obtained the lower bound n^2/4 for even n via a Hamiltonian-cycle construction, but did not fully justify the matching upper bound (e.g. stated “at most one quarter are good” without a complete argument). 2. Proved the upper bound n^2/4 for even n using the mod-4 restriction, but left a small gap in showing that all good starting squares must lie in the same congruence class (e.g. did not rigorously justify why the path/cycle is uniquely forced from a corner or another anchoring configuration). 3. Gave a complete odd-n impossibility proof and the even-n framework, but made a localized mistake in the corner/local-configuration forcing step (or omitted checking a boundary/local case), while the rest of the solution is correct and would yield the stated maximum.

Construction task:
For the specific case $n=64$, determine a valid initial direction diagram that maximizes the number of "good squares". Provide an explicit construction for this diagram.

Construction requirements:
- Output a single Python expression that evaluates to a $64 \times 64$ list of lists of integers.
- The integers must be in $\{0, 1, 2, 3\}$, representing the initial arrow directions: 0 for right, 1 for up, 2 for left, and 3 for down.
- The output must be a pure Python expression (e.g., a list comprehension). Do not include any explanations, comments, markdown formatting, print statements, assignments, function definitions, imports, classes, asserts, or loops outside of comprehensions.
- Prioritize using list comprehensions, conditional expressions, and integer constants to generate a compact, regular, and reproducible expression.
- Put ONLY the Python expression inside the construction block.

Reference construction:
[[(((0 if c < 63 else 3) if r == 0 else (1 if c == 0 else ((2 if c > 1 else (3 if r < 63 else 2)) if r % 2 == 1 else (0 if c < 63 else 3)))) - (c if r == 0 else (4096 - r if c == 0 else (r * 63 + 64 - c if r % 2 == 1 else r * 63 + c)))) % 4 for c in range(64)] for r in range(64)]

Verifier code:
import sys

def verify():
    payload = sys.stdin.read().strip()
    if not payload:
        print("Empty input.")
        return

    try:
        # Evaluate the payload to obtain the 64x64 grid
        # eval is used here to properly parse list comprehensions as required by the instruction
        grid = eval(payload)
    except Exception as e:
        print(f"Failed to parse input: {e}")
        return

    # Validate structural correctness
    if type(grid) is not list:
        print("Grid must be a list.")
        return
    if len(grid) != 64:
        print(f"Grid must have exactly 64 rows, got {len(grid)}.")
        return
    
    flat_grid = [0] * 4096
    for i, row in enumerate(grid):
        if type(row) is not list:
            print(f"Row {i} is not a list.")
            return
        if len(row) != 64:
            print(f"Row {i} must have exactly 64 elements, got {len(row)}.")
            return
        for j, val in enumerate(row):
            if type(val) is not int or val not in {0, 1, 2, 3}:
                print(f"Element at ({i}, {j}) is not an integer in {{0, 1, 2, 3}}.")
                return
            flat_grid[(i << 6) | j] = val

    # Simulation setup
    visited = [0] * 4096
    attempt = 0
    good_squares_count = 0

    # Simulate snail movement from every possible starting square
    for r in range(64):
        for c in range(64):
            attempt += 1
            curr_r, curr_c = r, c
            success = True
            
            for t in range(4096):
                # Check out-of-bounds
                if curr_r < 0 or curr_r > 63 or curr_c < 0 or curr_c > 63:
                    success = False
                    break
                
                idx = (curr_r << 6) | curr_c
                
                # Check if already visited in the current attempt
                if visited[idx] == attempt:
                    success = False
                    break
                
                # Mark as visited
                visited[idx] = attempt
                
                # Calculate current direction with 90-degree counterclockwise rotation (adding 1 mod 4 per step)
                d = (flat_grid[idx] + t) & 3
                
                # Update coordinates
                if d == 0:     # right
                    curr_c += 1
                elif d == 1:   # up
                    curr_r -= 1
                elif d == 2:   # left
                    curr_c -= 1
                else:          # down
                    curr_r += 1
            
            # After 4096 steps, check if it successfully returned to the start
            if success and curr_r == r and curr_c == c:
                good_squares_count += 1

    # Verify that the maximum number of good squares is achieved
    if good_squares_count != 1024:
        print(f"Expected 1024 good squares, but got {good_squares_count}.")
        return

    print("True")

if __name__ == "__main__":
    verify()