单词搜索
https://www.lintcode.com/problem/123/?utm_source=sc-libao-ql
board = ["ABCE","SFCS","ADEE"]word = "ABCCED"trueLast updated
https://www.lintcode.com/problem/123/?utm_source=sc-libao-ql
board = ["ABCE","SFCS","ADEE"]word = "ABCCED"trueLast updated
board = ["z"]word = "z"truefrom typing import (
List,
)
from functools import lru_cache
class Solution:
"""
@param board: A list of lists of character
@param word: A string
@return: A boolean
"""
def exist(self, board: List[List[str]], word: str) -> bool:
# write your code here
#dp[m][n] = dp[m-1][n] or dp[m][n-1]
if not word:
return True
if not board:
return False
directions= {(0,1),(0,-1),(1,0),(-1,0)}
n,m = len(board),len(board[0])
def helper(x:int, y:int, i:int) -> bool:
if i == len(word):
return True
if not (0<=x< n and 0<=y<m) or word[i] != board[x][y]:
return False
temp = board[x][y]
board[x][y] = '#'
for dx,dy in directions:
nx,ny = x+dx, y+dy
if helper(nx,ny,i+1):
return True
board[x][y] = temp
return False
for i in range(n):
for j in range(m):
if board[i][j] == word[0] and helper(i,j,0):
return True
return False