All problems

Problem 287

Word Search

Medium · 20 pts · Matrix, Backtracking, Depth-First Search

Problem

You are given a grid of uppercase letters and a word. Decide whether the word can be traced in the grid: start at any cell holding the first letter, and move each time to a horizontally or vertically adjacent cell holding the next letter. Diagonal moves are not allowed, and a cell may be used at most once in the same word. Try every starting cell and use a depth-first search with backtracking: mark a cell as used while exploring from it, and unmark it when you return, so it is available to other paths.

Input

First line: R and C. Next R lines: C uppercase letters. Last line: the word.

Output

Print YES or NO.

Constraints

1 <= R, C <= 6; 1 <= word length <= 15

Example input

3 4
ABCE
SFCS
ADEE
ABCCED

Example output

YES

Explanation

Start at the A in the top-left corner, move right to B and then C, down to the C below it, down again to the E in the bottom row, and left to D. That spells A, B, C, C, E, D without reusing a cell, so the answer is YES.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: All Non-Empty Subsets Next: Sudoku Solver