Created
August 15, 2020 09:54
-
-
Save red-avtovo/7bf373714d0d78f5b9f50e280271c7f1 to your computer and use it in GitHub Desktop.
Find word on board
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[cfg(test)] | |
mod test { | |
#[test] | |
fn word() { | |
let board = vec![ | |
vec!['A','B','C','E'], | |
vec!['S','F','C','S'], | |
vec!['A','D','E','E'] | |
]; | |
let board2 = vec![ | |
vec!['A','B','C','E'], | |
vec!['S','F','E','S'], | |
vec!['A','D','E','E'] | |
]; | |
assert_eq!(exist(board.clone(), String::from("ABCCED")), true); | |
assert_eq!(exist(board.clone(), String::from("SEE")), true); | |
assert_eq!(exist(board.clone(), String::from("ABCB")), false); | |
assert_eq!(exist(board2.clone(), String::from("ABCESEEEFS")), true); | |
assert_eq!(exist(vec![vec!['A']], String::from("A")), true); | |
assert_eq!(exist(vec![vec!['a','a']], String::from("aaa")), false); | |
} | |
pub fn exist(mut board: Vec<Vec<char>>, word: String) -> bool { | |
let chars:Vec<char> = word.chars().collect(); | |
find_first(&board, chars[0]).into_iter() | |
.map(|(i,j)| { | |
find_around(&mut board, &chars, 1, i, j) | |
}) | |
.collect::<Vec<bool>>() | |
.contains(&true) | |
} | |
fn find_first(board: &Vec<Vec<char>>,ch: char) -> Vec<(usize,usize)> { | |
board.iter().enumerate().flat_map(|(i,line)| { | |
line.into_iter() | |
.enumerate() | |
.filter(|(_,c)| { **c == ch}) | |
.map(move |(j,_)| { (i,j) } ) | |
}) | |
.collect() | |
} | |
fn find_around(board: &mut Vec<Vec<char>>,chars: &Vec<char>, ci: usize, i: usize, j: usize) -> bool { | |
if ci >= chars.len() { | |
return true | |
} | |
let cur_c = chars[ci-1]; | |
let c = chars[ci]; | |
let width = board[0].len(); | |
let height = board.len(); | |
let mut res = false; | |
board[i][j]='_'; | |
//up | |
if (i as i32 -1) >= 0 && board[i-1][j]==c { | |
res = find_around(board, chars, ci+1, i-1, j); | |
} | |
//down | |
if !res && (i+1) < height && board[i+1][j]==c { | |
res = find_around(board, chars, ci+1, i+1, j); | |
}; | |
//left | |
if !res && (j as i32 -1) >=0 && board[i][j-1]==c { | |
res = find_around(board, chars, ci+1, i, j-1); | |
} | |
//right | |
if !res && (j+1) < width && board[i][j+1]==c { | |
res = find_around(board, chars, ci+1, i, j+1); | |
} | |
board[i][j]=cur_c; | |
res | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Runtime: 8 ms, faster than 93.48% of Rust online submissions for Word Search.
Memory Usage: 3.5 MB, less than 67.39% of Rust online submissions for Word Search.
https://leetcode.com/problems/word-search