atcoder#AGC059E. [AGC059E] Grid 3-coloring

[AGC059E] Grid 3-coloring

Score : 14001400 points

Problem Statement

You have an N×NN \times N grid board. You want to color all cells in 33 colors so that no two adjacent (edge-sharing) cells have the same color.

You have already painted the border of the board. Determine if you can color the rest of the board properly.

More precisely, you are given a string SS of length 4N44N-4 consisting of characters 1, 2, and 3. The string denotes the colors of the cells on the border, starting from the cell (1,1)(1, 1), in clockwise order. Strictly speaking, the ii-th character of SS denotes the color of the cell:

  • (1,i)(1, i) for 1iN11 \le i \le N-1
  • (i(N1),N)(i - (N-1), N) for Ni2N2N \le i \le 2N-2
  • (N,3N1i)(N, 3N - 1 - i) for 2N1i3N32N-1 \le i \le 3N-3
  • (4N2i,1)(4N-2 - i, 1) for 3N2i4N43N-2 \le i \le 4N-4.

Here, (r,c)(r,c) denotes the cell in the rr-th row and the cc-th column.

It is guaranteed that no two adjacent cells on the border have the same color.

Solve TT test cases for each input file.

Constraints

  • 1T51041 \le T \le 5 \cdot 10^4
  • 3N21053 \le N \le 2 \cdot 10^5
  • SS is a string of length 4N44N-4 consisting of characters 1, 2, and 3.
  • SiSi+1S_i \neq S_{i+1} for 1i4N51 \le i \le 4N-5, and S4N4S1S_{4N-4} \neq S_1.
  • The sum of NN in one input file doesn't exceed 21052\cdot 10^5.
  • All numbers in the input are integers.

Input

Input is given from Standard Input in the following format:

TT

case1case_1

case2case_2

\vdots

caseTcase_T

Each case is in the following format:

NN

SS

Output

For each test case, output YES if there is a way to color the rest of the board in 33 colors properly, and NO otherwise. You can output each letter in any case (upper or lower).

4
3
12312312
4
121212121212
7
321312312312121212121321
7
321312312312121312121321
NO
YES
NO
YES

It can be shown that there is no way to properly color the rest of the board in the first and the third test cases. The proper colorings for the second and fourth test cases are shown below.