#C508. Sequence Finder in a 2D Grid

    ID: 48689 Type: Default 1000ms 256MiB

Sequence Finder in a 2D Grid

Sequence Finder in a 2D Grid

You are given a 2D grid of integers and a sequence of integers. Your task is to determine if the sequence appears in the grid as a contiguous block, horizontally, vertically, or diagonally (both down-right and down-left).

More formally, given an \(N \times M\) grid \(A\) and a sequence \(S\) of length \(L\), the sequence is considered to be present if there exists a starting position \((i,j)\) and a direction \((dx, dy)\) (where \((dx,dy)\) is one of \((0,1), (1,0), (1,1), (1,-1)\)) such that for every \(0 \leq k < L\), we have \[ A_{i + k \cdot dx, j + k \cdot dy} = S_k \] with all indices valid in the grid. If such a configuration exists, output "YES", otherwise output "NO".

Note: The sequence of length 1 is always considered found if the element exists in the grid.

inputFormat

The input is given via standard input in the following format:

  • The first line contains two integers \(N\) and \(M\) representing the number of rows and columns of the grid.
  • The next \(N\) lines each contain \(M\) integers separated by spaces representing the grid.
  • The following line contains a single integer \(L\), the length of the sequence.
  • The last line contains \(L\) integers separated by spaces representing the sequence to be searched in the grid.

outputFormat

Output a single line containing "YES" if the sequence is found in the grid (in any contiguous horizontal, vertical, or diagonal direction), otherwise output "NO".

## sample
5 5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
4
7 8 9 10
YES