-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0212-word-search-ii.rs
93 lines (72 loc) · 2.18 KB
/
0212-word-search-ii.rs
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
93
#[derive(Default, Debug, Clone)]
struct Trie {
is_word_end: bool,
children: [Option<Box<Trie>>; 26],
}
impl Solution {
pub fn find_words(mut board: Vec<Vec<char>>, words: Vec<String>) -> Vec<String> {
let mut trie = Trie::new();
let (m, n) = (board.len(), board[0].len());
for word in words{
trie.insert(word);
}
let mut word = String::new();
let mut res = vec![];
for i in 0..m{
for j in 0..n{
Self::dfs(&mut board, &mut trie, &mut res, &mut word, i, j);
}
}
res
}
pub fn dfs(
board: &mut Vec<Vec<char>>,
mut trie: &mut Trie,
res: &mut Vec<String>,
word: &mut String,
i: usize,
j: usize
){
let (m, n) = (board.len(), board[0].len());
if i!= usize::MAX &&
j!= usize::MAX &&
i < m &&
j < n &&
board[i][j] != '#'
{
let c = board[i][j];
// mark as visited
board[i][j] = '#';
if let Some(ref mut curr_trie) = trie.children[char_index(c)]{
trie = curr_trie.as_mut();
word.push(c);
if trie.is_word_end{
res.push(word.clone());
trie.is_word_end = false;
}
for (x, y) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]{
Self::dfs(board, trie, res, word, x, y);
}
word.pop();
}
board[i][j] = c;
}
}
}
impl Trie {
fn new() -> Self {
Default::default()
}
fn insert(&mut self, word: String) {
let mut trie = self;
for c in word.chars(){
trie = trie.children[char_index(c)]
.get_or_insert(Box::new(Trie::new()))
.as_mut();
}
trie.is_word_end = true;
}
}
pub fn char_index(c: char) -> usize{
c as usize - 'a' as usize
}