-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path212 Word Search II.py
92 lines (73 loc) · 2.3 KB
/
212 Word Search II.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally
or vertically neighboring. The same letter cell may not be used more than once in a word.
For example,
Given words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Return ["eat","oath"].
Note:
You may assume that all inputs are consist of lowercase letters a-z.
Author: Rajeev Ranjan
"""
class TrieNode(object):
def __init__(self, char):
self.char = char
self.word = None
self.children = {} # map from char to TrieNode
def __repr__(self):
return repr(self.char)
class Trie(object):
def __init__(self):
self.root = TrieNode(None)
def add(self, word):
word = word.lower()
cur = self.root
for c in word:
if c not in cur.children:
cur.children[c] = TrieNode(c)
cur = cur.children[c]
cur.word = word
class Solution:
def __init__(self):
self.dirs = [(0, 1), (0, -1), (-1, 0), (1, 0)]
def findWords(self, board, words):
"""
Trie+dfs
pure Trie solution
:param board: a list of lists of 1 length string
:param words: a list of string
:return: a list of string
"""
trie = Trie()
for word in words:
trie.add(word)
ret = set()
marked = set()
for i in xrange(len(board)):
for j in xrange(len(board[0])):
self.dfs(board, i, j, trie.root, marked, ret)
return list(ret)
def dfs(self, board, i, j, parent, marked, ret):
"""
:type parent: TrieNode
"""
m = len(board)
n = len(board[0])
marked.add((i, j))
c = board[i][j]
if c in parent.children:
cur = parent.children[c]
if cur.word:
ret.add(cur.word)
for dir in self.dirs:
row = i+dir[0]
col = j+dir[1]
if 0 <= row < m and 0 <= col < n and (row, col) not in marked:
self.dfs(board, row, col, cur, marked, ret)
marked.remove((i, j))