Wednesday, April 23, 2014

Leetcode (Python): Word Search

Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

Solution:

Using a backtracking algorithm, we could use an extra grid O($n^2$) to mark the used cells so far.
If we were ensured that a certain symbol would not appear in the grid, we could change the cells to mark that have been used, making the algorithm to use constant space. For instance, to pass the leetcode test, the symbol '$' was tried and it did work as shown in the following code.

class Solution:
    # @param board, a list of lists of 1 length string
    # @param word, a string
    # @return a boolean
    def exist(self, board, word):
        solution = False
        for i in range(0,len(board)):
            for j in range(0, len(board[0])):
                solution = solution or self.existRec(board, word, i, j, 0)
        return solution
        
    def existRec(self, board, word, row, col, index):
        if row < 0 or row>=len(board) or col<0 or col>=len(board[0]) or  board[row][col]!=word[index]:
            return False
        if index==len(word)-1:
            return True
        board[row][col] = "$"
        solution = self.existRec(board, word, row-1, col, index+1) or self.existRec(board, word, row+1, col, index+1) or self.existRec(board, word, row, col-1, index+1) or self.existRec(board, word, row, col+1, index+1)
        board[row][col] = word[index]
        return solution

No comments :

Post a Comment