Word Search
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. Tags: Matrix
Try It!
Discussion
Video
Solution
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
if word == '':
return False
visited = [[False for j in range(len(board[0]))] for i in range(len(board))]
for i in range(len(board)):
for j in range(len(board[0])):
if self.dfs(board, i, j, visited, word):
return True
return False
def dfs(self, board, i, j, visited, word):
if word == '':
return True
if i < 0 or i >= len(board):
return False
if j < 0 or j >= len(board[0]):
return False
if visited[i][j]:
return False
if word[0] != board[i][j]:
return False
visited[i][j] = True
hasWord = self.dfs(board, i - 1, j, visited, word[1:]) \
or self.dfs(board, i + 1, j, visited, word[1:]) \
or self.dfs(board, i, j - 1, visited, word[1:]) \
or self.dfs(board, i, j + 1, visited, word[1:])
visited[i][j] = False
return hasWord