Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

algorithm - leetcode 212 word search II bugs using trie

Here is my solution:

class Solution(object):
    def findWords(self, board, words):
        WORD_KEY = '$'
        trie = {}
        for word in words:
            node = trie
            for letter in word:
                # retrieve the next node; If not found, create a empty node.
                node = node.setdefault(letter, {})
            # mark the existence of a word in trie node
            node[WORD_KEY] = word
        
        rowNum = len(board)
        colNum = len(board[0])
        
        matchedWords = []
        
        def helper(row,col,trie):
            if trie.keys()[0]==WORD_KEY:
                matchedWords.append(trie[WORD_KEY])
                return
            if row>len(board)-1 or row<0 or col>len(board[0])-1 or col<0:
                return
            if board[row][col] == '*':
                return
            if board[row][col] in trie:
                for (rowOffset, colOffset) in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
                    temp=board[row][col]
                    board[row][col]='*'
                    helper(row+rowOffset,col+colOffset,trie[temp])
                    board[row][col]=temp
            else:
                return
         
        for i in range(len(board)):
            for j in range(len(board[0])):
                helper(i,j,trie) 
        return matchedWords             

Recursion is always my biggest issue, and it is hard to find the mistake, I Want to know how I get it wrong with my code. The wrong output is such below: ["oath","oath","oath","oath","eat","eat","eat","eat"], each repeated 4 times

instead of just [oath,eat]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...