From fd099c827574310dc9c7f8cf21578bd68d822b98 Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Mon, 25 Jul 2022 20:05:22 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200037.=E8=A7=A3=E6=95=B0?= =?UTF-8?q?=E7=8B=AC=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0037.解数独 Rust版本 --- problems/0037.解数独.md | 46 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) 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