I'm running into an issue solving leetcode 79 word search using Python.
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can 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.
I'm trying to use a queue of characters and a BFS to look if a word exists on the board but the solution seems to work for certain words and not others. For example in the first testcase, the order of visited seems to go [[0, 0], [0, 1], [0, 2], [1, 2], [0, 3]] instead of the expected [[0, 0], [0, 1], [0, 2], [1, 2], [2, 2], [2, 1]]. I'm not sure if there's some mistake I'm overlooking (other than only testing from one startpoint, which I hope to fix after fixing this issue).
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
rows,cols=len(board),len(board[0])
directions=[[1,0],[-1,0],[0,1],[0,-1]]
word=str(word)
mq=list(word)
visited=[]
startlist=[]
#find all start points
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j]==mq[0]:
if [i,j] not in startlist:
startlist.append([i,j])
def bfs(r,c):
q=collections.deque()
q.append([r,c])
visited.append([r,c])
if board[r][c]==mq[0]:
mq.pop(0)
while q:
x,y=q.popleft()
for dx,dy in directions:
row,col=x+dx,y+dy
if row in range(rows):
if col in range(cols):
if mq:
if board[row][col]==mq[0]:
if [row,col] not in visited:
mq.pop(0)
visited.append([row,col])
q.append([row,col])
x,y=startlist[0]
bfs(x,y)
if not mq:
return True
else:
return False
````