forked from aylei/leetcode-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn0079_word_search.rs
130 lines (123 loc) · 3.39 KB
/
n0079_word_search.rs
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
/**
* [79] Word Search
*
* Given a 2D board and a word, find if the word exists in the grid.
*
* The word can 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.
*
* Example:
*
*
* board =
* [
* ['A','B','C','E'],
* ['S','F','C','S'],
* ['A','D','E','E']
* ]
*
* Given word = "ABCCED", return true.
* Given word = "SEE", return true.
* Given word = "ABCB", return false.
*
*
*/
pub struct Solution {}
// submission codes start here
// TODO: use HashSet to record visited pos
impl Solution {
pub fn exist(board: Vec<Vec<char>>, word: String) -> bool {
if board.is_empty() || word.len() < 1 {
return false;
}
let (height, width) = (board.len(), board[0].len());
if height < 1 || width < 1 {
return false;
}
let seq: Vec<char> = word.chars().collect();
for i in 0..height * width {
if Solution::dfs(
i / width,
i % width,
&seq[..],
&board,
vec![],
height,
width,
) {
return true;
}
}
false
}
fn dfs(
x: usize,
y: usize,
seq: &[char],
board: &Vec<Vec<char>>,
mut visited: Vec<(usize, usize)>,
height: usize,
width: usize,
) -> bool {
if seq[0] != board[x][y] {
return false;
}
if seq.len() < 2 {
return true;
}
visited.push((x, y));
return (x > 0
&& !visited.contains(&(x - 1, y))
&& Solution::dfs(x - 1, y, &seq[1..], board, visited.clone(), height, width))
|| (x + 1 < height
&& !visited.contains(&(x + 1, y))
&& Solution::dfs(x + 1, y, &seq[1..], board, visited.clone(), height, width))
|| (y > 0
&& !visited.contains(&(x, y - 1))
&& Solution::dfs(x, y - 1, &seq[1..], board, visited.clone(), height, width))
|| (y + 1 < width
&& !visited.contains(&(x, y + 1))
&& Solution::dfs(x, y + 1, &seq[1..], board, visited.clone(), height, width));
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_79() {
assert_eq!(Solution::exist(vec![vec!['a']], "a".to_owned()), true);
assert_eq!(
Solution::exist(
vec![
vec!['A', 'B', 'C', 'E'],
vec!['S', 'F', 'C', 'S'],
vec!['A', 'D', 'E', 'E'],
],
"ABCCED".to_owned()
),
true
);
assert_eq!(
Solution::exist(
vec![
vec!['A', 'B', 'C', 'E'],
vec!['S', 'F', 'C', 'S'],
vec!['A', 'D', 'E', 'E'],
],
"SEE".to_owned()
),
true
);
assert_eq!(
Solution::exist(
vec![
vec!['A', 'B', 'C', 'E'],
vec!['S', 'F', 'C', 'S'],
vec!['A', 'D', 'E', 'E'],
],
"ABCB".to_owned()
),
false
);
}
}