Last active
April 23, 2023 01:25
-
-
Save kperath/1f6e63238d8ae682779db40c628478aa to your computer and use it in GitHub Desktop.
My solution to wordsearch 2 on LC: https://leetcode.com/problems/word-search-ii/ a new test case was added that causes TLE for python unless words are removed from the trie which I show here.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class TrieNode: | |
| def __init__(self): | |
| self.children = {} | |
| self.ref = 0 # number of references (ie. size of each map) | |
| self.end = False | |
| def add_word(self, word): | |
| node = self | |
| node.ref += 1 | |
| for c in word: | |
| if c not in node.children: | |
| node.children[c] = TrieNode() | |
| node = node.children[c] | |
| node.ref += 1 | |
| node.end = True | |
| def remove_word(self, word): | |
| node = self | |
| node.ref -= 1 | |
| for c in word: | |
| # note: could add early exit here is node.ref == 0 | |
| node = node.children[c] | |
| node.ref -= 1 | |
| node.end = False # ex. ABC, ABC, ABCD don't want to add ABC twice | |
| class Solution: | |
| def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: | |
| res = [] | |
| trie = TrieNode() | |
| for word in words: | |
| trie.add_word(word) | |
| def dfs(r, c, visited, t, s): | |
| if (r, c) in visited: | |
| return | |
| if r < 0 or r == len(board) or c < 0 or c == len(board[0]): | |
| return | |
| curr = board[r][c] # current character | |
| if curr not in t.children: | |
| return | |
| if t.children[curr].ref <= 0: | |
| return | |
| visited.add((r,c)) # add to visited set down here or we'd have to remove it in earlier returns too | |
| if t.children[curr].end: # word found | |
| res.append(s+curr) | |
| trie.remove_word(s+curr) # remove from root (prevents TLE on python solution) | |
| dfs(r+1, c, visited, t.children[curr], s+curr) | |
| dfs(r-1, c, visited, t.children[curr], s+curr) | |
| dfs(r, c+1, visited, t.children[curr], s+curr) | |
| dfs(r, c-1, visited, t.children[curr], s+curr) | |
| visited.remove((r, c)) # backtrack! (undo visited path) | |
| for r in range(len(board)): | |
| for c in range(len(board[0])): | |
| dfs(r,c,set(),trie,"") | |
| return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment