From 3bd387df7cde50b6fada28aa824841f4c842921d Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sun, 24 Dec 2023 09:42:46 +0800 Subject: [PATCH] =?UTF-8?q?Update0037.=E8=A7=A3=E6=95=B0=E7=8B=AC=EF=BC=8C?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0037.解数独.md | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/problems/0037.解数独.md b/problems/0037.解数独.md index 1763063e..d96e59df 100644 --- a/problems/0037.解数独.md +++ b/problems/0037.解数独.md @@ -756,6 +756,59 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public void SolveSudoku(char[][] board) + { + BackTracking(board); + } + public bool BackTracking(char[][] board) + { + for (int i = 0; i < board.Length; i++) + { + for (int j = 0; j < board[0].Length; j++) + { + if (board[i][j] != '.') continue; + for (char k = '1'; k <= '9'; k++) + { + if (IsValid(board, i, j, k)) + { + board[i][j] = k; + if (BackTracking(board)) return true; + board[i][j] = '.'; + } + } + return false; + } + + } + return true; + } + public bool IsValid(char[][] board, int row, int col, char val) + { + for (int i = 0; i < 9; i++) + { + if (board[i][col] == val) return false; + } + for (int i = 0; i < 9; i++) + { + if (board[row][i] == val) return false; + } + int startRow = (row / 3) * 3; + int startCol = (col / 3) * 3; + for (int i = startRow; i < startRow + 3; i++) + { + for (int j = startCol; j < startCol + 3; j++) + { + if (board[i][j] == val) return false; + } + } + return true; + } +} +```