212. Word Search II
Description
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.
Example 1:
Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] Output: ["eat","oath"]
Example 2:
Input: board = [["a","b"],["c","d"]], words = ["abcb"] Output: []
Constraints:
m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j]
is a lowercase English letter.1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i]
consists of lowercase English letters.- All the strings of
words
are unique.
Solutions
Solution: Trie + Backtracking
- Time complexity: O(mn*max(words[i].length))
- Space complexity: O(words[i])
JavaScript
js
/**
* @param {character[][]} board
* @param {string[]} words
* @return {string[]}
*/
const findWords = function (board, words) {
const m = board.length;
const n = board[0].length;
const result = [];
const trie = { children: new Map() };
const backtracking = (row, col, node = trie) => {
if (row < 0 || col < 0 || row >= m || col >= n) return;
const value = board[row][col];
const nextNode = node.children.get(value);
if (value === '#' || !nextNode) return;
if (nextNode.word) {
result.push(nextNode.word);
nextNode.word = null;
}
if (!nextNode.children.size) {
node.children.delete(value);
return;
}
board[row][col] = '#';
backtracking(row + 1, col, nextNode);
backtracking(row - 1, col, nextNode);
backtracking(row, col + 1, nextNode);
backtracking(row, col - 1, nextNode);
board[row][col] = value;
};
for (const word of words) {
let node = trie;
for (const char of word) {
const nextNode = node.children.get(char) ?? { children: new Map() };
node.children.set(char, nextNode);
node = nextNode;
}
node.word = word;
}
for (let row = 0; row < m; row++) {
for (let col = 0; col < n; col++) {
backtracking(row, col);
}
}
return result;
};