Skip to content

Commit f518942

Browse files
committed
problem: 0079 word search
1 parent 4af1622 commit f518942

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

0079 Word Search/0079 Word Search.md

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# 0079. Word Search
2+
3+
* Difficulty: medium
4+
* Link: https://leetcode.com/problems/word-search/
5+
* Topics: Array-String, Matrix, Backtracking
6+
* highlight: 暴力解
7+
8+
# Clarification
9+
10+
1. Check the inputs and outputs
11+
- INPUT:List[List[int]]
12+
- OUTPUT:boolean
13+
14+
# Naive Solution
15+
16+
### Thought Process
17+
18+
1. 每個 node 去比對
19+
- Implement
20+
21+
```python
22+
class Solution:
23+
def exist(self, board: List[List[str]], word: str) -> bool:
24+
25+
if not board or not board[0] or not word:
26+
return False
27+
28+
rows = len(board)
29+
columns = len(board[0])
30+
lenW = len(word)
31+
visited = set()
32+
33+
def isValid(row, col):
34+
return ((0 <= row < rows) and (0 <= col < columns))
35+
36+
def searchWords(r, c, i):
37+
if word[i] == board[r][c] and i == lenW-1:
38+
return True
39+
40+
visited.add((r,c))
41+
directions = [(-1,0), (0,1), (1,0), (0,-1)]
42+
for dx, dy in directions:
43+
newR, newC = r + dx, c + dy
44+
if not isValid(newR, newC) or not board[newR][newC] or (newR,newC) in visited: continue
45+
if word[i+1] == board[newR][newC] and searchWords(newR, newC, i+1):
46+
return True
47+
visited.remove((r, c))
48+
return False
49+
50+
for r in range(rows):
51+
for c in range(columns):
52+
if board[r][c] == word[0] and searchWords(r, c, 0):
53+
return True
54+
return False
55+
```
56+
57+
58+
### Complexity
59+
60+
- Time complexity:O(N*M) * 4^len(word)
61+
- Space complexity:
62+
63+
### Note
64+
65+
- `r in range(R)` 這個的效能很低,要進行判斷是還是使用 `0 <= r < R`
66+
- 因為這個而 time Limit exceeded

0 commit comments

Comments
 (0)