diff --git a/problems/0037.解数独.md b/problems/0037.解数独.md index 626e9d97..8b196890 100644 --- a/problems/0037.解数独.md +++ b/problems/0037.解数独.md @@ -488,6 +488,52 @@ function solveSudoku(board: string[][]): void { }; ``` +### Rust + +```Rust +impl Solution { + fn is_valid(row: usize, col: usize, val: char, board: &mut Vec>) -> bool{ + for i in 0..9 { + if board[row][i] == val { return false; } + } + for j in 0..9 { + if board[j][col] == val { + return false; + } + } + let start_row = (row / 3) * 3; + let start_col = (col / 3) * 3; + for i in start_row..(start_row + 3) { + for j in start_col..(start_col + 3) { + if board[i][j] == val { return false; } + } + } + return true; + } + + fn backtracking(board: &mut Vec>) -> bool{ + for i in 0..board.len() { + for j in 0..board[0].len() { + if board[i][j] != '.' { continue; } + for k in '1'..='9' { + if Self::is_valid(i, j, k, board) { + board[i][j] = k; + if Self::backtracking(board) { return true; } + board[i][j] = '.'; + } + } + return false; + } + } + return true; + } + + pub fn solve_sudoku(board: &mut Vec>) { + Self::backtracking(board); + } +} +``` + ### C ```C