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.
Given board =[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]
"ABCCED", -> returns
"SEE", -> returns
"ABCB", -> returns
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)): 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) or word != 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