File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ # 79. Word Search
3
+
4
+ use backtracking(DFS) to search for the word in the board.
5
+
6
+ ## Time and Space Complexity
7
+
8
+ ```
9
+ TC: O(n * m * 4^L)
10
+ SC: O(L)
11
+ ```
12
+
13
+ #### TC is O(n * m * 4^L):
14
+ - n is the number of rows in the board.
15
+ - m is the number of columns in the board.
16
+ - L is the length of the word.
17
+ - 4^L is the number of directions we can go at each step. (explores 4 branches recursively)
18
+
19
+ #### SC is O(L):
20
+ - modifying the board in-place to mark visited cells. = O(L)
21
+ '''
22
+ class Solution :
23
+ def exist (self , board : List [List [str ]], word : str ) -> bool :
24
+ rows = len (board )
25
+ cols = len (board [0 ])
26
+
27
+ def backtracking (i , j , word_index ): # TC: O(4^L), SC: O(L)
28
+ if word_index == len (word ):
29
+ return True
30
+
31
+ if i < 0 or i >= rows or j < 0 or j >= cols or board [i ][j ] != word [word_index ]:
32
+ return False
33
+
34
+ temp = board [i ][j ]
35
+ board [i ][j ] = "."
36
+
37
+ found = (
38
+ backtracking (i + 1 , j , word_index + 1 ) or
39
+ backtracking (i - 1 , j , word_index + 1 ) or
40
+ backtracking (i , j + 1 , word_index + 1 ) or
41
+ backtracking (i , j - 1 , word_index + 1 )
42
+ )
43
+ board [i ][j ] = temp
44
+
45
+ return found
46
+
47
+ for row in range (rows ): # TC: O(n * m)
48
+ for col in range (cols ):
49
+ if backtracking (row , col , 0 ):
50
+ return True
51
+
52
+ return False
You can’t perform that action at this time.
0 commit comments