Problem
Given an m x n
board
of characters and a list of strings words
, return all words on the board.
Each word must 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 in a word.
Examples
Example 1:
|
|
This is a follow up: Word Search 1 - Find if word exists
Solution
Method 1 - Backtracking and DFS
Similar to Word Search 1 - Find if word exists,this problem can be solved by DFS. However, this solution exceeds time limit.
|
|
Method 2 - DFS + Trie
If the current candidate does not exist in all words’ prefix, we can stop backtracking immediately. This can be done by using a trie structure.
Note that here we are passing visited
array, but in Method 1, we didn’t pass, as we were modifiying our board[][]
matrix by setting #
to mark visited.
|
|
Trie Class
|
|