Skip to content

Commit 035a36f

Browse files
added 79 word search
1 parent 6e49344 commit 035a36f

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

+13
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,21 @@ https://sebinsua.com/algorithmic-bathwater
55
https://sebinsua.com/assets/posts/algorithmic-bathwater/algorithmic-bathwater-1.svg
66

77

8+
# 79. Word Search
9+
Intuition: Explore all possible path to find a matching work hence backtracking
10+
11+
Approach:
12+
1. dfs i, j, word
13+
1. if word len is 0 return True
14+
2. if i or j out of boundary or word[0] is neq board[i][j] return false
15+
3. store board[i][j] in tmp and set board[i][j] to `#` // so that it can be avoided to revisit
16+
4. move all four direction for remaining word (word[1:]) and compute the result
17+
5. reset board[i][j] to original word
18+
6. return the computed result from all four direction move
19+
2. call dfs for each row and col of board
820

921

22+
----
1023
# 2405: Optimal Partition of String
1124

1225
Intuition: map to store the string char, if char already exists in map means with hit a non unique char, increase the count and reset the map

leetcode-py/79-word-search.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution:
2+
def exist(self, board: List[List[str]], word: str) -> bool:
3+
ROW = len(board)
4+
COL = len(board[0])
5+
6+
def dfs(i, j, word):
7+
#End of the word, hence true
8+
if len(word) == 0:
9+
return True
10+
# out of the boundary or char is not exist at i & j
11+
if i<0 or i>=ROW or j<0 or j>=COL or board[i][j] != word[0]:
12+
return False
13+
14+
# store in tmp and will be use in reset for next iteration
15+
tmp = board[i][j] # chose
16+
17+
# mark visited for current visit
18+
board[i][j] = "#"
19+
20+
#explore
21+
res = dfs(i+1, j, word[1:]) or dfs(i-1, j, word[1:]) or dfs(i, j+1, word[1:]) or dfs(i, j-1, word[1:])
22+
23+
#un-chose
24+
board[i][j] = tmp
25+
return res
26+
27+
for i in range(ROW):
28+
for j in range(COL):
29+
if dfs(i, j, word): #choice
30+
return True
31+
32+
return False

0 commit comments

Comments
 (0)