topic
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.
Thinking
With backtracking. Because once just take a character board are compared, so do not copy board, but directly modify the board value (indicates that the cell is used up), if nowhere, then modify the value of recovery.
def existSub(self,board,word,i,j):
if len(word) == 0:
return True
c = word[0:1]
temp = board[i][j]
board[i][j] = ""
option_i = [-1,1]
if i == 0:
option_i.remove(-1)
if i==len(board)-1:
option_i.remove(1)
option_j = [-1,1]
if j == 0:
option_j.remove(-1)
if j == len(board[0])-1:
option_j.remove(1)
for k in option_i:
if c == board[i+k][j]:
if self.existSub(board,word[1:],i+k,j):
return True
for k in option_j:
if c == board[i][j+k]:
if self.existSub(board,word[1:],i,j+k):
return True
board[i][j] = temp
return False
def exist(self, board: List[List[str]], word: str) -> bool:
if len(board)==0:
return False
c_start = word[0:1]
m,n = len(board),len(board[0])
for i in range(m):
for j in range(n):
if board[i][j] == c_start:
if self.existSub(board,word[1:],i,j):
return True
return False