Word Search in Python

Suppose we have a 2D board and a word, we have to find if the word is present in the grid or not. The words can be made from letters of sequentially adjacent cell, "adjacent" cells are those horizontally or vertically neighboring cells. We should not use the same letter cell more than once. So if the matrix is like −


Given words are say “ABCCED”, the answer will be true, for word “SEE”, it will be true, but for “ABCB” if will be false.

Let us see the steps −

  • We will solve this using recursive approach. So if the recursive method name is called find(), this takes matrix mat, word, row, col and index i. Initially the index i = 0

  • if i = length of words, then return True

  • if row >= row count of mat or row < 0 or col >= col count of mat or col < 0 or word[i] is not same as mat[row, col], then return false

  • mat[row, col] := “*”

  • res := find(mat, word, row + 1, col, i + 1) or find(mat, word, row - 1, col, i + 1) or find(mat, word, row, col + 1, i + 1) or find(mat, word, row, col - 1, i + 1)

  • mat[row, col] := word[i]

  • return res

  • The main task will be performed like −

  • n := row count and m := column count

  • for i in range 0 to n

    • for j in range 0 to m

      • if word[0] = mat[i, j]

        • if find(mat, word, i, j) is not false, then return true


Let us see the following implementation to get better understanding −

class Solution(object):
   def exist(self, board, word):
      :type board: List[List[str]]
      :type word: str
      :rtype: bool
      n =len(board)
      m = len(board[0])
      for i in range(n):
         for j in range(m):
            if word[0] == board[i][j]:
               if self.find(board,word,i,j):
                  return True
      return False
   def find(self, board,word,row,col,i=0):
      if i== len(word):
         return True
      if row>= len(board) or row <0 or col >=len(board[0]) or col<0 or word[i]!=board[row][col]:
         return False
      board[row][col] = '*'
      res = self.find(board,word,row+1,col,i+1) or self.find(board,word,row-1,col,i+1) or                   self.find(board,word,row,col+1,i+1) or self.find(board,word,row,col-1,i+1)
      board[row][col] = word[i]
      return res




Published on 03-Feb-2020 10:10:36