Problem: 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. 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]