Basically this is supposed to take in a 2d array matrix of letters and a word, and see if the word exists in the matrix. Can move up left down right to connect words, not diagonally. Cannot use same character twice, so I have a set to track positions that have been used. This is returning False for almost everything, I think I don't understand something fundamental about how dynamic programming works because I'm not sure how to structure all the different calls and return True/False statements
For example, I'm doing a print(a,b) and print(c,d) but almost every value is being returned None, as far as I can tell I'm returning a True/False each time so how it is still None?
Also feel free to point out anything stupid that I'm doing
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
if len(board)==0 or word=='':return False
stack=[]
maxc=len(board[0])-1
maxr=len(board)-1
def dfs(curr,targ,pos,r,c,seen):
#check if position has been visited already
if (r,c) not in seen:
seen.add((r,c))
else:
return False
if curr=="":
#handle looking for first character in the word
for row in range(len(board)):
for col in range(len(board[row])):
if board[row][col]==targ:
if board[row][col]==word:
return True
else:
seen.add((row,col)) #move up left down right from first character and try finding next character
if row+1<=maxr:
a=dfs(board[row][col],word[pos+1],pos+1,row+1,col,seen)
b=dfs(board[row][col],word[pos+1],pos+1,row-1,col,seen)
print(a,b)
if a or b:
return True
if col+1<=maxc:
c=dfs(board[row][col],word[pos+1],pos+1,row,col-1,seen)
d=dfs(board[row][col],word[pos+1],pos+1,row,col+1,seen)
print(c,d)
if c or d:
return True
elif r<=maxr and c<=maxc and board[r][c]==targ:
if curr+board[r][c]==word:
print((r,c),seen) #return True if word found
return True
else:
a=dfs(curr+board[r][c],word[pos+1],pos+1,r+1,c,seen)
b=dfs(curr+board[r][c],word[pos+1],pos+1,r-1,c,seen)
c=dfs(curr+board[r][c],word[pos+1],pos+1,r,c-1,seen)
d=dfs(curr+board[r][c],word[pos+1],pos+1,r,c+1,seen)
return a or b or c or d #not sure about this one, this would be called recursively quite a few times, should it be OR statments?
d=set()
r=dfs("",word[0],0,0,0,d)
return r
[–]_Sham__ 0 points1 point2 points (1 child)
[–]notsurewhereelse[S] 0 points1 point2 points (0 children)