Word Search


Problem Statement

You are playing word search!

The rules of the game is simple: You are given an n×mn \times m grid of letters. You want to find if a given word, ww, exists on a straight line in the grid of letters.

For example, if the grid you are playing on is as follows:

Code 1
WGTNPOTSFXQQ
OVOEWPCNRRLX
BDZVNXWLCXJM
NBEZPRLGXHVU
OTTPDIMJSYPJ
XNEKTUFLSFVF
JKPYJHJCYVPR
FLAUQHFWKVVA
RIKDMPJFNUJG
VTDVCECFCPXK

and if you're asked to find the word DEPTH from it, you would be able to find it with the starting letter D starting from 22nd column, 33rd row:

Code 2
............
............
.D..........
..E.........
...P........
....T.......
.....H......
............
............
............

The word can go in any direction as long as it is in a straight line: East, North, South, West, North-East, North-West, South-East, or South-West.

As a smart kid like you are who even attends MAPS workshops, you have decided to write yourself a little algorithm that could solve word searches for you.

Input

Your first line will contain nn and mm as space-separated integers. nn and mm represents the size of the letter grid.

Your next line will contain ww, a string of the word you are trying to search for.

Your next mm lines will contain nn letters each, representing a single row of the letter grid.

Output

The string FOUND if the word ww is present in the letter grid, nope otherwise.

Constraints

For all test cases:

  • 1≤n,m≤1041 \le n,m \le 10^4
  • 1≤∣w∣≤max(n,m)1 \le |w| \le \text{max}\left(n, m\right); that is, the word ww will always be able to fit on the grid.

Example 1

Input 1
12 10
DEPTH
WGTNPOTSFXQQ
OVOEWPCNRRLX
BDZVNXWLCXJM
NBEZPRLGXHVU
OTTPDIMJSYPJ
XNEKTUFLSFVF
JKPYJHJCYVPR
FLAUQHFWKVVA
RIKDMPJFNUJG
VTDVCECFCPXK
Output 1
FOUND

Example 2

Input 2
4 7
MONASH
QKNP
PAOA
SNMA
UHAJ
UNHS
MBSY
AOAE
Output 2
nope

Example 3

Input 3
40 36
SUPERCALIFRAGILISTICEXPIALIDOCIOUS
OOTFOBAIZIWIUDEKMUYTWIAAZLQEPQQYVFILJEVX
DNRRGLJRHJDFILAWZXCPJGGOFDKAXDLIDFDLLZUK
WXGCCMCWJIBTTDDTQSBFNFWRNQZCNAXUVKAHNNUO
MWAH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GGKFJWVADPVGAOONDNWJWLAZMFXVXJMAZFK
LPLYIFXIJJKLBMVJRCCJUJMPVFQTQXMOBQWVEFYX
LDHRJBZKCAEJVVPZGRIZZETCNZIYCQACBMWGCAEJ
MKJTIQKZJGGKKNNAHEPTGKAZJWNVFNKMRPMOBFJN
OCIWIMHTGJZIXPULNPWYIGNQYRONTAUIPXXUXAVP
EFREVDIOYVIKYXQTBUJGWDTNIIHHERDXVODYWYRI
RINBUWOQZXBKFRVVKSYXFBJLHFIIAHHMVJRGLTCO


Output 3
FOUND

Python Template

Code 3
n, m = map(int, input().split())
word = input()
board = [list(input()) for _ in range(m)]

# print(...)

Comments0


No comments yet

Be the first to comment.

New comment


Log in to join the discussion.