|
| 1 | +#[inline(always)] |
| 2 | +pub fn encode(c : char) -> u8 { |
| 3 | + c as u8 - b'A' + 1 |
| 4 | +} |
| 5 | + |
| 6 | +#[inline] |
| 7 | +pub fn encode_word(mut word : String, counter : &mut [i8]) -> u128 { |
| 8 | + let mut res : u128 = 0; |
| 9 | + let end_char = encode(word.chars().next_back().unwrap()) as usize; |
| 10 | + let start_char = encode(word.chars().next().unwrap()) as usize; |
| 11 | + |
| 12 | + if counter[end_char] > counter[start_char] { |
| 13 | + while let Some(c) = word.pop() { |
| 14 | + res <<= 6; |
| 15 | + let byte = encode(c); |
| 16 | + counter[byte as usize] -= 1; |
| 17 | + res |= byte as u128; |
| 18 | + } |
| 19 | + } else { |
| 20 | + for c in word.chars() { |
| 21 | + res <<= 6; |
| 22 | + let byte = encode(c); |
| 23 | + counter[byte as usize] -= 1; |
| 24 | + res |= byte as u128; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + res |
| 29 | +} |
| 30 | + |
| 31 | +impl Solution { |
| 32 | + pub fn exist(board: Vec<Vec<char>>, word: String) -> bool { |
| 33 | + if board.len() * board[0].len() < word.len() { |
| 34 | + return false; |
| 35 | + } |
| 36 | + |
| 37 | + let mut counter : [i8; 60] = [0; 60]; |
| 38 | + let board : Vec<Vec<u8>> = board |
| 39 | + .into_iter() |
| 40 | + .map(|row| |
| 41 | + row.into_iter().map(|ele| { |
| 42 | + let mut res = encode(ele); |
| 43 | + counter[res as usize] += 1; |
| 44 | + res |
| 45 | + }) |
| 46 | + .collect() |
| 47 | + ).collect(); |
| 48 | + |
| 49 | + let word = encode_word(word, &mut counter); |
| 50 | + |
| 51 | + if counter.into_iter().any(|&count| count < 0) { |
| 52 | + return false; |
| 53 | + } |
| 54 | + |
| 55 | + let mut visited : Vec<Vec<bool>> = vec![vec![false; board[0].len()]; board.len()]; |
| 56 | + |
| 57 | + for i in 0..board.len() { |
| 58 | + for j in 0..board[0].len() { |
| 59 | + if Self::backtrack(word, &board, i, j, &mut visited) { |
| 60 | + return true; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + false |
| 66 | + } |
| 67 | + |
| 68 | + #[inline(always)] |
| 69 | + pub fn backtrack( |
| 70 | + mut word : u128, |
| 71 | + board : &[Vec<u8>], |
| 72 | + i : usize, j : usize, |
| 73 | + visited : &mut [Vec<bool>] |
| 74 | + ) -> bool { |
| 75 | + if i >= board.len() || j >= board[i].len() || word as u8 & 0b111111 != board[i][j] || visited[i][j] { |
| 76 | + return false; |
| 77 | + } |
| 78 | + |
| 79 | + visited[i][j] = true; |
| 80 | + |
| 81 | + ({ word >>= 6; word == 0 } ) |
| 82 | + ||(Self::backtrack(word, board, i + 1, j, visited) ) |
| 83 | + ||(Self::backtrack(word, board, i, j + 1, visited) ) |
| 84 | + ||(Self::backtrack(word, board, i - 1, j, visited) ) |
| 85 | + ||(Self::backtrack(word, board, i, j - 1, visited) ) |
| 86 | + ||({ |
| 87 | + visited[i][j] = false; |
| 88 | + false |
| 89 | + }) |
| 90 | + |
| 91 | + } |
| 92 | +} |
0 commit comments