Problem
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
1 |
|
Explanation
-
First, we can iterate the board and find the character that is matched with the first character of the word. Then, think of this character as the middle, we recursivly check its top, bottom, left, right element if match with the second character of the word.
-
Special case is we cannot use the same character twice, so we create a
isUsed
table that have the same size as the board. If the character is used, then we mark it as true in theisUsed
table. Or if the current word match, then we mark the current word as a random character such as#
, after the recursive function, we backtrack the current word to its original character.
Solution
1 |
|