Skip to content

Commit 16f1ee4

Browse files
committedDec 2, 2020
feat: word-search
1 parent 529fea0 commit 16f1ee4

File tree

2 files changed

+55
-13
lines changed

2 files changed

+55
-13
lines changed
 

‎trie.implement-trie-prefix-tree.py

+3-13
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,7 @@ def insert(self, word: str) -> None:
1717
"""
1818
tree = self.lookup
1919
for a in word:
20-
if a not in tree:
21-
tree[a] = {}
22-
23-
tree = tree[a]
20+
tree = tree.setdefault(a, {})
2421
tree['#'] = '#'
2522

2623

@@ -30,10 +27,7 @@ def search(self, word: str) -> bool:
3027
"""
3128
tree = self.lookup
3229
for a in word:
33-
if a not in tree:
34-
return False
35-
36-
tree = tree[a]
30+
tree = tree.setdefault(a, {})
3731

3832
if '#' in tree:
3933
return True
@@ -47,11 +41,7 @@ def startsWith(self, prefix: str) -> bool:
4741
"""
4842
tree = self.lookup
4943
for a in prefix:
50-
if a not in tree:
51-
return False
52-
53-
tree = tree[a]
54-
44+
tree = tree.setdefault(a, {})
5545
return True
5646

5747

‎trie.word-search.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""
6+
79. 单词搜索
7+
https://leetcode-cn.com/problems/word-search/
8+
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
9+
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
10+
"""
11+
12+
def exist(self, board: List[List[str]], word: str) -> bool:
13+
# 定义方向,上下右左
14+
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
15+
16+
def check(i: int, j: int, k: int) -> bool:
17+
if board[i][j] != word[k]:
18+
return False
19+
if k == len(word) - 1:
20+
return True
21+
22+
visited.add((i, j))
23+
result = False
24+
for di, dj in directions:
25+
newi, newj = i + di, j + dj
26+
if 0 <= newi < len(board) and 0 <= newj < len(board[0]):
27+
if (newi, newj) not in visited:
28+
if check(newi, newj, k + 1):
29+
result = True
30+
break
31+
32+
visited.remove((i, j))
33+
return result
34+
35+
h, w = len(board), len(board[0])
36+
visited = set()
37+
for i in range(h):
38+
for j in range(w):
39+
if check(i, j, 0):
40+
return True
41+
42+
return False
43+
44+
45+
so = Solution()
46+
board = [
47+
['A','B','C','E'],
48+
['S','F','C','S'],
49+
['A','D','E','E']
50+
]
51+
52+
print(so.exist(board, 'ABCCEDF'))

0 commit comments

Comments
 (0)