Red and Black Stepping Stones

No attempts yetTime limit9sMemory limit256 MB

Problem

John and Bessie play a game on a directed graph, and both of them know the graph. The vertices are numbered 11 through nn, the edges between vertices have a direction, and every edge is red or black. Apart from the graph there is one queue of size kk, and both players see the colors inside it.

At the start John puts his piece on vertex 11 and the queue is empty. Bessie fills the queue with red and black colors until it is full, and then the main game begins.

A turn runs like this.

  1. John removes one color from the front of the queue.
  2. John picks an outgoing edge of that color at the vertex where his piece stands, and moves the piece along that edge. He may pick an edge that leads back to the same vertex.
  3. One slot of the queue is now empty, so Bessie appends one color at the back.

Bessie wins if John cannot move his piece because his vertex has no outgoing edge of the color he removed. John wins if he keeps the game going forever. Bessie sees John's situation both when she first fills the queue and when she appends a color on a turn, and John sees all kk colors in the queue when he picks an edge.

Given the graph, find the smallest queue size kk for which John wins no matter how Bessie picks colors.

Input

The first line has the number of test cases tt (1t201 \le t \le 20).

The first line of each test case has the number of vertices nn (1n121 \le n \le 12). The next nn lines hold the adjacency matrix of the red edges. Each line has nn integers separated by spaces, and the jj-th number on the ii-th line is 11 if there is a red edge from ii to jj and 00 if there is none. The next nn lines hold the adjacency matrix of the black edges in the same format. The piece always starts on vertex 11.

In every test case where John can win, the smallest kk is at most 1212.

Output

For each test case print the smallest kk for which John wins on its own line. If John cannot win for any queue size, print 00.