Under construction

Still being built. Things may change

Ripple Effect

Interview

Time limit2sMemory limit128 MB

Summary
Validate a filled Ripple Effect puzzle grid by checking polyomino region digit ranges and minimum-distance spacing rules for repeated numbers in rows and columns.
Level

Medium4 of 10

Topics
Union-find, Simulation, Implementation
Solved
No attempts yet

Problem

Determine whether the given filled grid satisfies the rules of a Ripple Effect puzzle.

A Ripple Effect puzzle is played on a rectangular grid divided into several polyominoes. A polyomino is a shape made by joining one or more equal-sized squares edge to edge.

Every cell of the grid contains one positive integer. The placement is valid only if all of the following rules hold.

  • In a polyomino of size k, each integer from 1 through k must appear exactly once.
  • If the same number x appears more than once in the same row or in the same column, then any two such x cells must have at least x other cells between them. Equivalently, their row or column positions must differ by at least x + 1.

In this problem, every polyomino has size at most 8.

Input

The first line contains the number of test cases T. (T <= 100)

For each test case, the first line contains two integers R and C. (4 <= R, C <= 15)

The next R lines each contain a string of length C describing the numbers written in the grid. Each character is d_i, where 1 <= d_i <= 8.

The next R lines each contain C integers describing which neighboring cells each cell is connected to. Call this R x C table descr. Each value satisfies 0 <= descr(r,c) <= 15.

The value descr(r,c) is determined by the directions in which cell (r,c) is connected to adjacent cells.

descr(r,c) = 0
if connected((r,c), (r-1,c)): descr(r,c) += 1  # UP
if connected((r,c), (r,c+1)): descr(r,c) += 2  # RIGHT
if connected((r,c), (r+1,c)): descr(r,c) += 4  # DOWN
if connected((r,c), (r,c-1)): descr(r,c) += 8  # LEFT

For example, a cell belonging to a polyomino of size 1 is not connected to any neighboring cell, so its value is 0. A cell connected to both the cell above and the cell below has value 5.

Output

For each test case, print valid if the grid satisfies the rules, and print invalid otherwise.

Examples1

  1. Example 1

    Input
    2
    6 6
    241321
    312432
    131243
    423121
    214312
    141231
    2 12 4 4 6 8
    4 5 1 5 5 4
    5 1 0 5 1 5
    3 8 4 1 4 1
    2 10 9 2 9 4
    0 2 10 10 8 1
    6 6
    421321
    312432
    131243
    423121
    214312
    141231
    2 12 4 4 6 8
    4 5 1 5 5 4
    5 1 0 5 1 5
    3 8 4 1 4 1
    2 10 9 2 9 4
    0 2 10 10 8 1
    
    Expected output
    valid
    invalid