File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 시간복잡도: O(N*M*4^limit) limit: word의 길이
2
+ # 공간복잡도: O(N)
3
+ class Solution :
4
+ def exist (self , board : List [List [str ]], word : str ) -> bool :
5
+ m = len (board )
6
+ n = len (board [0 ])
7
+ limit = len (word )
8
+ visited = [[False for _ in range (n )] for _ in range (m )]
9
+ dx = [0 , 0 , - 1 , 1 ]
10
+ dy = [- 1 , 1 , 0 , 0 ]
11
+
12
+ target = 0
13
+
14
+ def dfs (x , y , idx ):
15
+
16
+ if idx == limit - 1 :
17
+ return True
18
+
19
+ for i in range (4 ):
20
+ nx , ny = x + dx [i ], y + dy [i ]
21
+
22
+ if 0 <= nx < m and 0 <= ny < n and not visited [nx ][ny ] and board [nx ][ny ] == word [idx + 1 ]:
23
+ visited [nx ][ny ] = True
24
+ if dfs (nx , ny , idx + 1 ):
25
+ return True
26
+ visited [nx ][ny ] = False
27
+
28
+ return False
29
+
30
+ for i in range (m ):
31
+ for j in range (n ):
32
+ if board [i ][j ] == word [target ]:
33
+ visited [i ][j ] = True
34
+ if dfs (i , j , 0 ):
35
+ return True
36
+ visited [i ][j ] = False
37
+
38
+ return False
You can’t perform that action at this time.
0 commit comments