File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ from typing import List
2+
3+
4+ class Solution :
5+ def exist (self , board : List [List [str ]], word : str ) -> bool :
6+ def dfs (row , col , k ):
7+ if k == len (word ):
8+ return True
9+
10+ # out of range
11+ if row < 0 or row >= len (board ) or col < 0 or col >= len (board [0 ]):
12+ return False
13+
14+ # char not found
15+ if board [row ][col ] != word [k ]:
16+ return False
17+
18+ temp = board [row ][col ]
19+
20+ # mark visited char
21+ board [row ][col ] = None
22+
23+ result = (
24+ dfs (row + 1 , col , k + 1 ) # top
25+ or dfs (row - 1 , col , k + 1 ) # bottom
26+ or dfs (row , col + 1 , k + 1 ) # right
27+ or dfs (row , col - 1 , k + 1 ) # left
28+ )
29+
30+ # restore char
31+ board [row ][col ] = temp
32+
33+ return result
34+
35+ for row in range (len (board )):
36+ for col in range (len (board [0 ])):
37+ if dfs (row , col , 0 ):
38+ return True
39+
40+ return False
You can’t perform that action at this time.
0 commit comments