Search for Word II
Given a 2-D grid of characters board and a list of strings words, return all words that are present in the grid.
For a word to be present it must be possible to form the word with a path in the board with horizontally or vertically neighboring cells. The same cell may not be used more than once in a word.
Example 1:
Input:
board = [
["a","b","c","d"],
["s","a","a","t"],
["a","c","k","e"],
["a","c","d","n"]
],
words = ["bat","cat","back","backend","stack"]
Output: ["cat","back","backend"]
Example 2:
Input:
board = [
["x","o"],
["x","o"]
],
words = ["xoxo"]
Output: []
Constraints:
1 <= board.length, board[i].length <= 10
board[i] consists only of lowercase English letter.
1 <= words.length <= 100
1 <= words[i].length <= 10
words[i] consists only of lowercase English letters.
All strings within words are distinct.
Solution
Compared with basic Search for Word, this problem involves multiple queries. For one query, we have to go through the whole matrix and apply DFS, which consume O ( n × m × Len ( w o r d ) ) O(n\times m\times \text{Len}(word)) O(n×m×Len(word)) time complexity. If we simply repeat this process on every query, the time complexity is O ( n × m × ∑ w ∈ w o r d s Len ( w ) ) O(n\times m\times \sum_{w\in words}\text{Len}(w)) O(n×m×∑w∈wordsLen(w