-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path37-Sudoku_Solver.rs
More file actions
51 lines (44 loc) · 1.25 KB
/
Copy path37-Sudoku_Solver.rs
File metadata and controls
51 lines (44 loc) · 1.25 KB
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
impl Solution {
pub fn solve_sudoku(board: &mut Vec<Vec<char>>) {
Self::backtrack(board);
}
fn backtrack(board: &mut Vec<Vec<char>>) -> bool {
for r in 0..9 {
for c in 0..9 {
if board[r][c] == '.' {
for num in '1'..='9' {
if Self::is_valid(board, r, c, num) {
board[r][c] = num;
if Self::backtrack(board) {
return true;
}
board[r][c] = '.';
}
}
return false;
}
}
}
true
}
fn is_valid(board: &Vec<Vec<char>>, r: usize, c: usize, num: char) -> bool {
for i in 0..9 {
if board[r][i] == num {
return false;
}
if board[i][c] == num {
return false;
}
}
let box_r = (r / 3) * 3;
let box_c = (c / 3) * 3;
for i in 0..3 {
for j in 0..3 {
if board[box_r + i][box_c + j] == num {
return false;
}
}
}
true
}
}