Word Search II

BacktrackingTrie
https://leetcode.com/problems/word-search-ii

# Solution

Let nn be the number of rows and mm be the number of columns of the board. Let ww be the number of words and ll be the average length of word to be matched.

# Trie

B/c search is done in backtrack, no need to implement search in Trie.

See more about Trie in Interview Algorithms.

Complexity

time: O(wl+nm3wl)O(wl + nm \cdot 3^wl)
space: O(wl+l)=O(wl)O(wl + l) = O(wl)

from collections import defaultdict
class TrieNode:
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.is_word = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        curr = self.root
        for char in word:
            curr = curr.children[char]
        curr.is_word = True

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        n, m = len(board), len(board[0])
        res = []
        trie = Trie()
        root = trie.root
        for word in words:
            trie.insert(word)

        def backtrack(i, j, curr, path):
            if curr.is_word:
                res.append(path)
                curr.is_word = False
            if i<0 or i>=n or j<0 or j>=m:
                return
            temp = board[i][j]
            curr = curr.children.get(temp)
            if not curr:
                return
            board[i][j] = '#'
            backtrack(i+1, j, curr, path+temp)
            backtrack(i-1, j, curr, path+temp)
            backtrack(i, j+1, curr, path+temp)
            backtrack(i, j-1, curr, path+temp)
            board[i][j] = temp

        for i in range(n):
            for j in range(m):
                backtrack(i, j, root, '')

        return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47