0

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
                        
                        ````

1 Answers1

0

There are several problems with the algorithm you are trying with:

  • visited should only collect the nodes on the current path. It is not right that other paths restrict the liberty of the current path.
  • mq.pop(0) will forever remove that character, but as you loop over different directions, all those iterations should compare against the same mq character... so this is wrong. Instead you should keep track of the index in mq to compare with. This could be stored with the row and column in the queue (as a third information).
  • bfs is only initiated on the first cell in startlist. All the other elements in startlist could have good positions to start with, but they are never tried.

This would be easier to implement (and use less memory) with DFS instead of BFS.

trincot
  • 317,000
  • 35
  • 244
  • 286