-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathword-search.rs
83 lines (72 loc) · 2.29 KB
/
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
#![allow(dead_code, unused, unused_variables)]
fn main() {}
struct Solution;
impl Solution {
pub fn exist(board: Vec<Vec<char>>, word: String) -> bool {
let word = word.as_bytes();
let mut board = board;
for i in 0..board.len() {
for j in 0..board[0].len() {
if board[i][j] as u8 == word[0] {
let x = board[i][j];
board[i][j] = '0';
if Self::scan(&mut board[..], &word[1..], (i, j)) {
return true;
}
board[i][j] = x;
}
}
}
false
}
fn scan(board: &mut [Vec<char>], word: &[u8], index: (usize, usize)) -> bool {
if word.len() == 0 {
return true;
}
if index.0 > 0 {
let x = board[index.0 - 1][index.1];
board[index.0 - 1][index.1] = '0';
if x != '0'
&& x as u8 == word[0]
&& Self::scan(board, &word[1..], (index.0 - 1, index.1))
{
return true;
}
board[index.0 - 1][index.1] = x;
}
if index.0 < board.len() - 1 {
let x = board[index.0 + 1][index.1];
board[index.0 + 1][index.1] = '0';
if x != '0'
&& x as u8 == word[0]
&& Self::scan(board, &word[1..], (index.0 + 1, index.1))
{
return true;
}
board[index.0 + 1][index.1] = x;
}
if index.1 > 0 {
let x = board[index.0][index.1 - 1];
board[index.0][index.1 - 1] = '0';
if x != '0'
&& x as u8 == word[0]
&& Self::scan(board, &word[1..], (index.0, index.1 - 1))
{
return true;
}
board[index.0][index.1 - 1] = x;
}
if index.1 < board[0].len() - 1 {
let x = board[index.0][index.1 + 1];
board[index.0][index.1 + 1] = '0';
if x != '0'
&& x as u8 == word[0]
&& Self::scan(board, &word[1..], (index.0, index.1 + 1))
{
return true;
}
board[index.0][index.1 + 1] = x;
}
false
}
}