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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
//! Word Search II [leetcode: word_search_ii](https://leetcode.com/problems/word-search-ii/) //! //! 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. //! //! **Example:** //! //! ``` //! Input: //! board = [ //! ['o','a','a','n'], //! ['e','t','a','e'], //! ['i','h','k','r'], //! ['i','f','l','v'] //! ] //! words = ["oath","pea","eat","rain"] //! //! Output: ["eat","oath"] //! ``` //! //! **Note:** //! //! 1. All inputs are consist of lowercase letters `a-z`. //! 2. The values of `words` are distinct. use std::collections::HashSet; const DIRS: [[i32; 2]; 4] = [[1, 0], [-1, 0], [0, 1], [0, -1]]; /// # Solutions /// /// # Approach : Trie and DFS /// /// * Time complexity: /// /// * Space complexity: /// * **It doesn't work, I'm sorry** /// /// ```rust /// use std::collections::HashSet; /// /// #[derive(Debug, Default)] /// pub struct Trie { /// is_end: bool, /// nodes: [Option<Box<Trie>>; 26], /// } /// /// impl Trie { /// /// fn new() -> Self { /// Default::default() /// } /// /// fn insert(&mut self, word: String) { /// let mut curr = self; /// for i in word.chars().map(|char| (char as u8 - 'a' as u8) as usize) { /// curr = curr.nodes[i].get_or_insert_with(|| Box::new(Trie::new())); /// } /// curr.is_end = true; /// } /// } /// /// impl Solution { /// const DIRS: [[i32; 2]; 4] = [[1, 0], [-1, 0], [0, 1], [0, -1]]; /// /// pub fn find_words(mut board: Vec<Vec<char>>, words: Vec<String>) -> Vec<String> { /// let rows = board.len(); /// let cols = board[0].len(); /// /// if rows == 0 || cols == 0 || words.len() == 0 { return vec![]; } /// /// let mut trie = Trie::new(); /// let mut result: HashSet<String> = HashSet::new(); /// /// for word in words { trie.insert(word); } /// /// for row in 0..rows { /// for col in 0..cols { /// let mut s = String::from(""); /// Self::_dfs(&mut board, &mut result, &mut s, row, col, &trie); /// } /// } /// /// result.into_iter().collect::<Vec<String>>() /// } /// /// pub fn _dfs(board: &mut Vec<Vec<char>>, /// result: &mut HashSet<String>, /// s: &mut String, /// row: usize, /// col: usize, /// trie: &Trie) { /// let mut curr = trie; /// if let Some(node) = trie.nodes[(board[row][col] as u8 - 'a' as u8) as usize].as_ref() { /// curr = node; /// s.push(board[row][col]); /// if curr.is_end { result.insert(s.clone()); } /// for d in Self::DIRS.iter() { /// let ni = (row as i32 + d[0]) as usize; /// let nj = (col as i32 + d[1]) as usize; /// if ni >= board.len() || nj >= board[0].len() || board[ni][nj] == '#' { continue; } /// /// let ch = board[row][col]; /// board[row][col] = '#'; /// Self::_dfs(board, result, s, ni, nj, curr); /// board[row][col] = ch; /// } /// } /// } /// } /// ``` /// pub fn find_words(mut board: Vec<Vec<char>>, words: Vec<String>) -> Vec<String> { let rows = board.len(); let cols = board[0].len(); if rows == 0 || cols == 0 || words.len() == 0 { return vec![]; } let mut trie = Trie::new(); let mut result: HashSet<String> = HashSet::new(); for word in words { trie.insert(word); } for row in 0..rows { for col in 0..cols { let mut s = String::from(""); _dfs(&mut board, &mut result, &mut s, row, col, &trie); } } result.into_iter().collect::<Vec<String>>() } pub fn _dfs(board: &mut Vec<Vec<char>>, result: &mut HashSet<String>, s: &mut String, row: usize, col: usize, trie: &Trie) { if let Some(node) = trie.nodes[(board[row][col] as u8 - 'a' as u8) as usize].as_ref() { let curr = node; s.push(board[row][col]); if curr.is_end { result.insert(s.clone()); } for d in DIRS.iter() { let ni = (row as i32 + d[0]) as usize; let nj = (col as i32 + d[1]) as usize; if ni >= board.len() || nj >= board[0].len() || board[ni][nj] == '#' { continue; } let ch = board[row][col]; board[row][col] = '#'; _dfs(board, result, s, ni, nj, curr); board[row][col] = ch; } } } #[derive(Debug, Default)] pub struct Trie { is_end: bool, nodes: [Option<Box<Trie>>; 26], } impl Trie { fn new() -> Self { Default::default() } fn insert(&mut self, word: String) { let mut curr = self; for i in word.chars().map(|char| (char as u8 - 'a' as u8) as usize) { curr = curr.nodes[i].get_or_insert_with(|| Box::new(Trie::new())); } curr.is_end = true; } }