Problem
Given an m x n
grid of characters board
and a string word
, return true
if word
exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example
Example 1:
$$ \begin{bmatrix} \colorbox{YellowOrange} A & \colorbox{YellowOrange} B & \colorbox{YellowOrange} C & E \\ S & F & \colorbox{YellowOrange} C & S \\ A & \colorbox{YellowOrange} D & \colorbox{YellowOrange} E & E \end{bmatrix} $$
|
|
Example 2: $$ \begin{bmatrix} A & B & C & E \\ S & F & C & \colorbox{YellowOrange} S \\ A & D & \colorbox{YellowOrange} E & \colorbox{YellowOrange} E \end{bmatrix} $$
|
|
Example 3: $$ \begin{bmatrix} A & B & C & E \\ S & F & C & S \\ A & D & E & E \end{bmatrix} $$
|
|
Follow up
Word Search 2 - Return All Words
Solution
This problem can be solve by using a typical DFS method and backtracking.
We need to make sure that we don’t visit the same character again, if it is already used in word search. We can either use hashSet or we can modify the board temporarily. We will use some char like #
OR *
whenever we use some char in board, and revert after checking and backtrack.
|
|
Time complexity = O(n*m* 4^len(word)) = O(4^n)