Word Search II in Python

PythonServer Side ProgrammingProgramming

Suppose we have a 2D board and a list of words. So from the dictionary, we have to find all words in the board. Here each word must be constructed from letters of sequentially adjacent cell, where the adjacent cells are those horizontally or vertically neighboring. We have to keep in mind that the same letter cell may not be used more than once in a word.

So if the input is like −

To solve this, we will follow these steps −

  • make an array result

  • Define a method called solve(), this will take board, d, i, j s

  • when either i or j are not in board row and column range respectively, return false

  • l := board[i, j]

  • if l is present in d, then

    • d := d[l], concatenate l with s

    • if # is in d and d[#] is not null, then

      • insert s into result

      • set d[#] := 0

    • board[i, j] := *

    • if i+1 < number of rows in board and board[i + 1, j] in d, then

      • call solve(board, d, i + 1, j, s)

    • if j+1 < number of columns in board and board[i, j+1] in d, then

      • call solve(board, d, i, j+1, s)

    • if i-1 > 0 and board[i - 1, j] in d, then

      • call solve(board, d, i - 1, j, s)

    • if j-1 > 0 and board[i, j-1] in d, then

      • call solve(board, d, i, j-1, s)

    • board[i, j] := l

  • define one method called insert(), this will take word and dictionary t

  • current := t

  • for i in word

    • if i is not in current, then current[i] := new map

    • current := current[i]

  • current[#] := 1

  • From the main method do the following −

  • create a map t

  • for word in words: call insert(word, t)

  • for each cell i, j in board − call solve(board, t, i, j)

  • return result


Let us see the following implementation to get better understanding −

 Live Demo

class Solution(object):
   def findWords(self, board, words):
      self.result = []
      t = {}
      for word in words:
      for i in range(len(board)):
         for j in range(len(board[0])):
      return self.result
   def solve(self,board,d,i,j,s=""):
      if i<0 or j<0 or i>=len(board) or j>=(len(board[0])):
      l = board[i][j]
      if l in d:
         d = d[l]
         if "#" in d and d['#']:
            d['#'] = 0
         board[i][j] = '*'
         if i+1<len(board) and board[i+1][j] in d :
         if j+1 < len(board[0]) and board[i][j+1] in d:
         if i-1>=0 and board[i-1][j] in d :
         if j-1>=0 and board[i][j-1] in d :
         board[i][j] = l
   def insert(self, word,t):
      current = t
      for i in word:
         if i not in current:
            current[i] = {}
         current =current[i]

ob = Solution()
print(ob.findWords([["o","a","a","n"],["e","t","e","a"],["i","h","k", "r"],["i","f","l","v"]],["oath","pea","tea","rain"]))




['oath', 'tea']
Updated on 26-May-2020 14:03:03