Word Search

This question was asked in Facebook:

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 =


word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

My Solution

We can see clearly this is a backtracking problem (depth-first search). By trying the letter from top left, and using DFS check if there are ways to construct the word vertically and horizontally. If we can’t find the solution, keep going to try different letter until we have tried all possibilities. This approach will cost O(n^2) to check all elements, plus O(b^m) where b is branching factor (in this case: 2) and m is maximum depth of the state space.

def word_exist(board, word):
  if not board or not word:
    return False
  for i in range(len(board)):
    for j in range(len(board[0])):
      if self.dfs(board, word, i, j):
        return True
  return False

# traverse the grid
def dfs(board, word, i, j):
  if not word:  # we have reached end of the word
    return True
  if i<0 or j<0 or i>=len(board) or j>=len(board[0]) or word[0] != board[i][j]:
    return False

  # we found the first letter
  tmp = board[i][j]  # store the letter in tmp var to do backtracking later
  board[i][j] = "#"  # mark as visited

  res = dfs(board, word[1:], i-1, j) or \
        dfs(board, word[1:], i+1, j) or \
        dfs(board, word[1:], i, j-1) or \
        dfs(board, word[1:], i, j+1)
  board[i][j] = tmp  # restore back the original letter
  return res

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s