mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Update0037.解数独,添加C#
This commit is contained in:
@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
|
Reference in New Issue
Block a user