-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword_search.rs
99 lines (90 loc) · 2.53 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
///
/// Problem: Word Search
///
/// Given an `m x n` grid of characters (`board`) and a string `word`, return **`true`** if `word` exists in the grid.
///
/// The word can be constructed **from letters of sequentially adjacent cells**, where:
/// - Cells are adjacent **horizontally or vertically**.
/// - The same letter cell **cannot be used more than once per search**.
///
/// **Example 1:**
/// ```plaintext
/// Input:
/// board =
/// [
/// ['A','B','C','E'],
/// ['S','F','C','S'],
/// ['A','D','E','E']
/// ]
/// word = "ABCCED"
/// Output: true
/// ```
///
/// **Example 2:**
/// ```plaintext
/// Input:
/// board =
/// [
/// ['A','B','C','E'],
/// ['S','F','C','S'],
/// ['A','D','E','E']
/// ]
/// word = "SEE"
/// Output: true
/// ```
///
/// **Example 3:**
/// ```plaintext
/// Input:
/// board =
/// [
/// ['A','B','C','E'],
/// ['S','F','C','S'],
/// ['A','D','E','E']
/// ]
/// word = "ABCB"
/// Output: false
/// ```
///
/// **Constraints:**
/// - `1 <= board.length, board[i].length <= 6`
/// - `1 <= word.length <= 15`
/// - `board` and `word` consist only of lowercase and uppercase English letters.
///
/// # Solution:
/// - **Time Complexity:** ``O(m * n * 4^L)`
/// - **Space Complexity:** `O(L)`, Recursion depth is L, the word length)
impl Solution {
pub fn exist(board: Vec<Vec<char>>, word: String) -> bool {
let (rows, cols) = (board.len(), board[0].len());
let word_chars: Vec<char> = word.chars().collect();
let mut board = board;
for i in 0..rows {
for j in 0..cols {
if Self::dfs(&mut board, &word_chars, 0, i as isize, j as isize) {
return true;
}
}
}
false
}
fn dfs(board: &mut Vec<Vec<char>>, word: &[char], index: usize, row: isize, col: isize) -> bool {
if index == word.len() {
return true;
}
if row < 0 || row >= board.len() as isize || col < 0 || col >= board[0].len() as isize {
return false;
}
if board[row as usize][col as usize] != word[index] {
return false;
}
let temp = board[row as usize][col as usize];
board[row as usize][col as usize] = '#';
let found = Self::dfs(board, word, index + 1, row + 1, col)
|| Self::dfs(board, word, index + 1, row - 1, col)
|| Self::dfs(board, word, index + 1, row, col + 1)
|| Self::dfs(board, word, index + 1, row, col - 1);
board[row as usize][col as usize] = temp;
found
}
}