|
| 1 | +pub struct Solution {} |
| 2 | +use std::collections::{HashMap, HashSet}; |
| 3 | +pub struct Trie { |
| 4 | + end: bool, |
| 5 | + children: HashMap<char, Trie>, |
| 6 | +} |
| 7 | +impl Trie { |
| 8 | + fn new() -> Self { |
| 9 | + Trie { |
| 10 | + end: false, |
| 11 | + children: HashMap::new(), |
| 12 | + } |
| 13 | + } |
| 14 | + fn insert(&mut self, word: String) { |
| 15 | + let mut cur = self; |
| 16 | + for c in word.chars() { |
| 17 | + let cur = cur.children.entry(c).or_insert(Trie::new()); |
| 18 | + } |
| 19 | + cur.end = true; |
| 20 | + } |
| 21 | +} |
| 22 | +impl Solution { |
| 23 | + pub fn find_words(board: Vec<Vec<char>>, words: Vec<String>) -> Vec<String> { |
| 24 | + let mut root = Trie::new(); |
| 25 | + for w in words { |
| 26 | + root.insert(w); |
| 27 | + } |
| 28 | + let mut visted: HashSet<(i32, i32)> = HashSet::new(); |
| 29 | + let mut res: Vec<String> = Vec::new(); |
| 30 | + fn dfs( |
| 31 | + row: i32, |
| 32 | + col: i32, |
| 33 | + node: &mut Trie, |
| 34 | + word: &str, |
| 35 | + board: &Vec<Vec<char>>, |
| 36 | + res: &mut Vec<String>, |
| 37 | + visited: &mut HashSet<(i32, i32)>, |
| 38 | + ) { |
| 39 | + if row < 0 |
| 40 | + || col < 0 |
| 41 | + || row as usize == board.len() |
| 42 | + || col as usize == board[0].len() |
| 43 | + || visited.contains(&(row, col)) |
| 44 | + || !node |
| 45 | + .children |
| 46 | + .contains_key(&board[row as usize][col as usize]) |
| 47 | + { |
| 48 | + return; |
| 49 | + } |
| 50 | + visited.insert((row, col)); |
| 51 | + |
| 52 | + let mut cur = node |
| 53 | + .children |
| 54 | + .get_mut(&board[row as usize][col as usize]) |
| 55 | + .unwrap(); |
| 56 | + let mut new_word = word.to_string(); |
| 57 | + new_word.push(board[row as usize][col as usize]); |
| 58 | + println!("{:?}", word); |
| 59 | + if cur.end { |
| 60 | + res.push(new_word.clone()); |
| 61 | + } |
| 62 | + dfs(row + 1, col, &mut cur, &new_word, board, res, visited); |
| 63 | + dfs(row + 1, col, &mut cur, &new_word, board, res, visited); |
| 64 | + dfs(row, col + 1, &mut cur, &new_word, board, res, visited); |
| 65 | + dfs(row, col - 1, &mut cur, &new_word, board, res, visited); |
| 66 | + visited.remove(&(row, col)); |
| 67 | + } |
| 68 | + let mut word = String::new(); |
| 69 | + for r in 0..board.len() { |
| 70 | + for c in 0..board[0].len() { |
| 71 | + let mut word: Vec<char> = Vec::new(); |
| 72 | + dfs( |
| 73 | + r as i32, |
| 74 | + c as i32, |
| 75 | + &mut root, |
| 76 | + &"", |
| 77 | + &board, |
| 78 | + &mut res, |
| 79 | + &mut visted, |
| 80 | + ); |
| 81 | + } |
| 82 | + } |
| 83 | + res |
| 84 | + } |
| 85 | +} |
0 commit comments