Given an m x n
grid of characters board
and a string word
, return true
if word
exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
class Solution:
def exist(self, b: List[List[str]], w: str) -> bool:
row, col = len(b), len(b[0])
p = set()
def dfs(r, c, i):
if i == len(w):
return True
if (
r<0 or
c<0 or
r>=row or
c>=col or
w[i]!=b[r][c] or
(r,c) in p
) : return False
p.add((r,c))
ans = (dfs(r+1,c,i+1) or
dfs(r-1,c,i+1) or
dfs(r,c+1,i+1) or
dfs(r,c-1,i+1))
p.remove((r,c))
return ans
for r in range(row):
for c in range(col):
if dfs(r,c,0): return True
return False
Explaination :
Comments
Post a Comment