Why is my solution to leetcode question 212. (Word Search II) failing for some cases?
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)]
res = set()
def dfs(r, c, word, char, visited):
if r < 0 or c < 0 or r >= len(board) or c >= len(board[0]) or \
board[r][c] != word[char] or (r, c) in visited:
return
visited.add((r, c))
if char == len(word) - 1:
if len(res) == 0 or res[-1] != word:
res.add(word)
return
for dr, dc in dirs:
dfs(r + dr, c + dc, word, char + 1, visited)
for word in words:
for r in range(len(board)):
for c in range(len(board[0])):
if board[r][c] == word[0]:
dfs(r, c, word, 0, set())
return list(res)
board =
[["a","b","c"],["a","e","d"],["a","f","g"]]
words =
["eaafgdcba","eaabcdgfa"]
Use Testcase
Output
["eaabcdgfa"]
Expected
["eaabcdgfa","eaafgdcba"]
Please help I've been staring at this for like 2 hours. It's passing 59 / 65 testcases, and I have no idea what's going wrong.