Word Search
Problem Statement
You are playing word search!
The rules of the game is simple: You are given an n×m grid of letters. You want to find if a given word, w, exists on a straight line in the grid of letters.
For example, if the grid you are playing on is as follows:
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 2nd column, 3rd row:
............
............
.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 n and m as space-separated integers. n and m represents the size of the letter grid.
Your next line will contain w, a string of the word you are trying to search for.
Your next m lines will contain n letters each, representing a single row of the letter grid.
Output
The string FOUND if the word w is present in the letter grid, nope otherwise.
Constraints
For all test cases:
- 1≤n,m≤104
- 1≤∣w∣≤max(n,m); that is, the word w will always be able to fit on the grid.
Example 1
12 10
DEPTH
WGTNPOTSFXQQ
OVOEWPCNRRLX
BDZVNXWLCXJM
NBEZPRLGXHVU
OTTPDIMJSYPJ
XNEKTUFLSFVF
JKPYJHJCYVPR
FLAUQHFWKVVA
RIKDMPJFNUJG
VTDVCECFCPXK
FOUND
Example 2
4 7
MONASH
QKNP
PAOA
SNMA
UHAJ
UNHS
MBSY
AOAE
nope
Example 3
40 36
SUPERCALIFRAGILISTICEXPIALIDOCIOUS
OOTFOBAIZIWIUDEKMUYTWIAAZLQEPQQYVFILJEVX
DNRRGLJRHJDFILAWZXCPJGGOFDKAXDLIDFDLLZUK
WXGCCMCWJIBTTDDTQSBFNFWRNQZCNAXUVKAHNNUO
MWAHYIAWGAFCEPFKLUJNKZKIRZMZXVKZRTJNNADR
BXNOKPUNCAECBZEAKOGRCTAUYLMZDRGQKFOLDBJZ
QITUYHPONZRH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VVPZGRIZZETCNZIYCQACBMWGCAEJ
MKJTIQKZJGGKKNNAHEPTGKAZJWNVFNKMRPMOBFJN
OCIWIMHTGJZIXPULNPWYIGNQYRONTAUIPXXUXAVP
EFREVDIOYVIKYXQTBUJGWDTNIIHHERDXVODYWYRI
RINBUWOQZXBKFRVVKSYXFBJLHFIIAHHMVJRGLTCO
FOUND
Python Template
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.