Skip to content

Commit 0f143c1

Browse files
committed
Word Search II
1 parent 26956a7 commit 0f143c1

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

212 Word Search II py3.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#!/usr/bin/python3
2+
"""
3+
Given a 2D board and a list of words from the dictionary, find all words in the board.
4+
5+
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally
6+
or vertically neighboring. The same letter cell may not be used more than once in a word.
7+
8+
For example,
9+
Given words = ["oath","pea","eat","rain"] and board =
10+
11+
[
12+
['o','a','a','n'],
13+
['e','t','a','e'],
14+
['i','h','k','r'],
15+
['i','f','l','v']
16+
]
17+
Return ["eat","oath"].
18+
Note:
19+
You may assume that all inputs are consist of lowercase letters a-z.
20+
"""
21+
from typing import List
22+
from collections import defaultdict
23+
24+
25+
dirs = [(0, 1), (0, -1), (-1, 0), (1, 0)]
26+
27+
28+
class TrieNode:
29+
def __init__(self):
30+
self.word = None
31+
self.children = defaultdict(TrieNode)
32+
33+
34+
class Solution:
35+
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
36+
root = self.construct(words)
37+
m, n = len(board), len(board[0])
38+
visited = [[False for _ in range(n)] for _ in range(m)]
39+
ret = set()
40+
for i in range(m):
41+
for j in range(n):
42+
self.dfs(board, visited, i, j, root, ret)
43+
44+
return list(ret)
45+
46+
def dfs(self, board, visited, i, j, cur, ret):
47+
m, n = len(board), len(board[0])
48+
visited[i][j] = True
49+
c = board[i][j]
50+
if c in cur.children:
51+
nxt = cur.children[c]
52+
if nxt.word is not None:
53+
ret.add(nxt.word)
54+
55+
for di, dj in dirs:
56+
I = i + di
57+
J = j + dj
58+
if 0 <= I < m and 0 <= J < n and not visited[I][J]:
59+
self.dfs(board, visited, I, J, nxt, ret)
60+
61+
visited[i][j] = False
62+
63+
def construct(self, words):
64+
root = TrieNode()
65+
for w in words:
66+
cur = root
67+
for c in w:
68+
cur = cur.children[c]
69+
cur.word = w
70+
71+
return root

0 commit comments

Comments
 (0)