https://leetcode.com/problems/word-search/description/
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.
Example:
board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] Given word = "ABCCED", return true. Given word = "SEE", return true. Given word = "ABCB", return false.
class Solution(object):
def check(self, arr, row, col, rest_word):
if self.board[row][col] != rest_word[0] or not arr[row][col]:
return False
if len(rest_word) == 1:
return True
arr[row][col] = False
# print self.board[row][col], row, col, arr
if row > 0 and self.check(arr, row - 1, col, rest_word[1:]):
return True
if col > 0 and self.check(arr, row, col - 1, rest_word[1:]):
return True
if row < len(self.board) - 1 and self.check(arr, row + 1, col, rest_word[1:]):
return True
if col < len(self.board[0]) - 1 and self.check(arr, row, col + 1, rest_word[1:]):
return True
arr[row][col] = True
return False
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
arr = [[True] * len(board[0]) for _ in range(len(board))]
self.board = board
for i in range(len(board)):
for j in range(len(board[0])):
if self.check(arr, i, j, word):
return True
return False