CSharp 实现数独算法 源代码
时间: 2023-11-10 12:56:20 浏览: 43
可以为您提供 CSharp 实现数独算法的源代码,以下是示例代码:
using System;
namespace SudokuSolver
{
class Program
{
static void Main(string[] args)
{
int[,] board = new int[,]
{
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0}
};
if (SolveSudoku(board))
{
Console.WriteLine("Sudoku solved:");
PrintBoard(board);
}
else
{
Console.WriteLine("Unable to solve Sudoku.");
}
}
static bool SolveSudoku(int[,] board)
{
int row = 0;
int col = 0;
bool isEmpty = true;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (board[i, j] == 0)
{
row = i;
col = j;
isEmpty = false;
break;
}
}
if (!isEmpty)
{
break;
}
}
if (isEmpty)
{
return true;
}
for (int num = 1; num <= 9; num++)
{
if (IsValid(board, row, col, num))
{
board[row, col] = num;
if (SolveSudoku(board))
{
return true;
}
else
{
board[row, col] = 0;
}
}
}
return false;
}
static bool IsValid(int[,] board, int row, int col, int num)
{
for (int i = 0; i < 9; i++)
{
if (board[row, i] == num)
{
return false;
}
if (board[i, col] == num)
{
return false;
}
int boxRow = 3 * (row / 3) + i / 3;
int boxCol = 3 * (col / 3) + i % 3;
if (board[boxRow, boxCol] == num)
{
return false;
}
}
return true;
}
static void PrintBoard(int[,] board)
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
Console.Write(board[i, j] + " ");
}
Console.WriteLine();
}
}
}
}