leetcode79 -- 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.

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:
def exist(self, board: List[List[str]], word: str) -> bool:
if len(board)==0 or len(board)==0:
return False

m, n = len(board), len(board)
visited = [[False for _ in range(n)] for _ in range(m)]
for i in range(m):
for j in range(n):
if self.search(board, word, 0, i, j, visited):
return True
return False

def search(self, board, word, idx, i, j, visited):
if idx==len(word):
return True
m,n = len(board),len(board)

if i<0 or j<0 or i>=m or j>=n or visited[i][j] or board[i][j] != word[idx]:
return False

visited[i][j]=True
res =any([self.search(board, word, idx+1, i-1,j,visited), self.search(board, word, idx+1, i+1,j, visited),
self.search(board, word, idx+1,i,j-1, visited),
self.search(board, word, idx+1, i, j+1, visited)])

visited[i][j] = False
return res



class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
if len(board)==0 or len(board)==0:
return False

m, n = len(board), len(board)
# visited = [[False for _ in range(n)] for _ in range(m)]
for i in range(m):
for j in range(n):
if self.search(board, word, 0, i, j):
return True
return False

def search(self, board, word, idx, i, j):
if idx==len(word):
return True
m,n = len(board),len(board)

if i<0 or j<0 or i>=m or j>=n or board[i][j] != word[idx]:
return False

# visited[i][j]=True
temp = board[i][j]
board[i][j] = '#'
res =any([self.search(board, word, idx+1, i-1,j), self.search(board, word, idx+1, i+1,j),
self.search(board, word, idx+1,i,j-1),
self.search(board, word, idx+1, i, j+1)])
# visited[i][j] = False
board[i][j] = temp
return res  