diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 74738eb..1677e89 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -169,4 +169,5 @@ mod p17_letter_combinations_of_a_phone_number; mod p77_combinations; mod p46_permutations; mod p39_combination_sum; -mod p22_generate_parentheses; \ No newline at end of file +mod p22_generate_parentheses; +mod p79_word_search; \ No newline at end of file diff --git a/src/problem/p79_word_search.rs b/src/problem/p79_word_search.rs new file mode 100644 index 0000000..40055b9 --- /dev/null +++ b/src/problem/p79_word_search.rs @@ -0,0 +1,78 @@ +/** + * [79] Word Search + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn exist(board: Vec>, word: String) -> bool { + let word: Vec = word.chars().collect(); + + let (m, n) = (board.len(), board[0].len()); + + let mut visited = vec![vec![false;n];m]; + for i in 0..m { + for j in 0..n { + if board[i][j] == word[0] { + if Self::search(&board, &word, &mut visited, i as i32, j as i32, 0) { + return true; + } + } + } + } + + false + } + + fn search(board: &Vec>, word: &Vec, visited: &mut Vec>, x: i32, y: i32, pos: usize) -> bool { + if pos == word.len() { + return true; + } + + let (m, n) = (board.len() as i32, board[0].len() as i32); + + if x < 0 || x >= m || y < 0 || y >= n { + return false; + } + + let (x_pos, y_pos) = (x as usize, y as usize); + + if visited[x_pos][y_pos] { + return false; + } + + visited[x_pos][y_pos] = true; + if board[x_pos][y_pos] == word[pos] { + if Self::search(board, word, visited, x + 1, y, pos + 1) { + return true; + } + + if Self::search(board, word, visited, x - 1, y, pos + 1) { + return true; + } + + if Self::search(board, word, visited, x, y + 1, pos + 1) { + return true; + } + + if Self::search(board, word, visited, x, y - 1, pos + 1) { + return true; + } + } + visited[x_pos][y_pos] = false; + + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_79() {} +}