|
| 1 | +# https://leetcode.com/problems/word-search-ii/ |
| 2 | +# |
| 3 | +# algorithms |
| 4 | +# Hard (27.72%) |
| 5 | +# Total Accepted: 100,953 |
| 6 | +# Total Submissions: 364,212 |
| 7 | +# beats 61.83% of python submissions |
| 8 | + |
| 9 | + |
| 10 | +class TrieNode(object): |
| 11 | + def __init__(self): |
| 12 | + self.children = [None] * 26 |
| 13 | + self.is_leaf = False |
| 14 | + |
| 15 | + |
| 16 | +class Solution(object): |
| 17 | + def findWords(self, board, words): |
| 18 | + """ |
| 19 | + :type board: List[List[str]] |
| 20 | + :type words: List[str] |
| 21 | + :rtype: List[str] |
| 22 | + """ |
| 23 | + trie_root = TrieNode() |
| 24 | + row, col = len(board), len(board[0]) |
| 25 | + |
| 26 | + for w in words: |
| 27 | + tmp = trie_root |
| 28 | + for ch in w: |
| 29 | + trie_idx = ord(ch) - 97 |
| 30 | + if tmp.children[trie_idx] is None: |
| 31 | + tmp.children[trie_idx] = TrieNode() |
| 32 | + tmp = tmp.children[trie_idx] |
| 33 | + tmp.is_leaf = True |
| 34 | + |
| 35 | + def recursive(i, j, root, path): |
| 36 | + ch = board[i][j] |
| 37 | + |
| 38 | + if ch == '#': |
| 39 | + return |
| 40 | + |
| 41 | + trie_idx = ord(ch) - 97 |
| 42 | + if root.children[trie_idx] is None: |
| 43 | + return |
| 44 | + |
| 45 | + path += ch |
| 46 | + board[i][j] = '#' |
| 47 | + if root.children[trie_idx].is_leaf: |
| 48 | + res[0] += path, |
| 49 | + root.children[trie_idx].is_leaf = False |
| 50 | + |
| 51 | + if i > 0: |
| 52 | + recursive(i - 1, j, root.children[trie_idx], path) |
| 53 | + |
| 54 | + if i < row - 1: |
| 55 | + recursive(i + 1, j, root.children[trie_idx], path) |
| 56 | + |
| 57 | + if j > 0: |
| 58 | + recursive(i, j - 1, root.children[trie_idx], path) |
| 59 | + |
| 60 | + if j < col - 1: |
| 61 | + recursive(i, j + 1, root.children[trie_idx], path) |
| 62 | + |
| 63 | + path = path[:-1] |
| 64 | + board[i][j] = ch |
| 65 | + |
| 66 | + res = [[]] |
| 67 | + |
| 68 | + for i in xrange(row): |
| 69 | + for j in xrange(col): |
| 70 | + recursive(i, j, trie_root, '') |
| 71 | + |
| 72 | + return res[0] |
0 commit comments