Word search - MarisaOJ: Marisa Online Judge

Word search

Time limit: 1000 ms
Memory limit: 256 MB
You are given a board of size $n \times m$ consisting of characters, and a word $S$. Write a program to determine if the word exists in the board. The word can be constructed from letters of sequentially adjacent cells, where "adjacent" cells are either horizontally neighboring or vertically neighboring, but not both. The same letter cell may not be used more than once. Considering the board: ``` abc def ``` In this board, the word search should follow the rule that only either horizontally or vertically neighboring cells are considered at a time, but not both simultaneously. - The word `abc` can be found in a horizontal path by moving from left to right in the first row. - The word `cb` can also be found in a horizontal path by moving from right to left in the first row. - The word `ad` can be found in a vertical path by moving in the first column. - However, the word `bcf` cannot be found as it requires both horizontal and vertical movements simultaneously, which is not allowed by the rule specified. ### Input - The first line contains two integers $n,m$. - The next $n$ lines, each line a string of length $m$ represeting the board. - The next line contains string $S$. ### Output - Print `YES` if the given string can be found, otherwise print `NO`. ### Constraints - $1 \le n \le 50$. - $1 \le |S| \le 50$. ### Example Input: ``` 6 4 mari aris risa isam sama amar marisa ``` Output: ``` YES ```