Stake Your Claim

Time limit1sMemory limit128 MB

Summary
On an n by n board with 1 to 10 empty squares, find the current player's optimal move and final score difference under optimal play.
Level

Hard8 of 10

Topics
Game theory, Backtracking, Graph, DFS
Solved
No attempts yet

Problem

Two players, 00 and 11, play on an n×nn \times n board. Some squares already hold a 0 or a 1, and the rest are empty. The players take turns, starting with player 00; on a turn, the current player writes their own number into one empty square. Play continues until the board is full.

When the board is full, each player's score is the size of the largest connected region of that player's number. A region is connected if you can travel between any two of its squares using only up, down, left, and right steps between squares holding the same number; diagonal steps do not connect squares. The player with the higher score wins and is awarded the difference between the two scores.

It is the current player's turn. The current player is player 00 when the board holds an equal number of 0s and 1s, and player 11 when it holds exactly one more 0 than 1. Assuming both players play optimally from now on, determine the best square for the current player to play and the best point total they can achieve, namely their own final score minus the opponent's final score (which may be negative).

Input

The input contains several test cases.

Each test case begins with a line containing a positive integer nn (n≤8n \le 8), the size of the board. The next nn lines describe the board from row 00 downward; each line has nn characters, each of which is 0, 1, or . (an empty square), with column 00 first. The board holds either the same number of 0s and 1s or exactly one more 0 than 1, and it has between 11 and 1010 empty squares.

A line containing a single 0 follows the last test case and must not be processed.

Output

For each test case, print one line with the best move and the best point total for the current player, in the format (row,col) total, using 00-based row and column indices. If several moves achieve the same best total, print the one that is smallest in lexicographic order of (row, col).

Examples2

  1. Example 1

    Input
    4
    01.1
    00..
    .01.
    ...1
    4
    0.01
    0.01
    1..0
    .1..
    0
    
    Expected output
    (1,2) 2
    (2,2) -1
    
  2. Example 2

    Input
    2
    0.
    .1
    0
    
    Expected output
    (0,1) 0