using System;
namespace 数独测试
{
internal class Program
{
static int[,] pu = new int[9, 9];
static void Main(string[] args)
{
//初始状态
int[,] pu_tep = {
{1, 0, 0, 0, 0, 0, 0, 4, 5},
{4, 0, 0, 7, 0, 0, 0, 0, 0},
{0, 5, 7, 0, 0, 0, 3, 8, 0},
{8, 0, 0, 5, 9, 0, 4, 0, 0},
{0, 0, 6, 8, 2, 0, 5, 0, 0},
{0, 0, 9, 0, 7, 3, 0, 0, 8},
{0, 1, 5, 0, 0, 0, 8, 6, 0},
{0, 0, 0, 0, 0, 8, 0, 0, 7},
{9, 7, 0, 0, 0, 0, 0, 0, 4}
};
pu = pu_tep;
if (SolveSudoku())
{
//打印
for (int x = 0; x < 9; x++)
{
for (int y = 0; y < 9; y++)
{
Console.Write(pu[x, y] + " ");
}
Console.WriteLine();
}
Console.ReadKey();
}
else
{
Console.WriteLine("无解");
Console.ReadKey();
}
}
static public bool isSafe(int row, int col, int num)
{
for (int i = 0; i < 9; i++)
{
if (pu[row, i] == num || pu[i, col] == num)
return false;
}
int boxRowStart = row - row % 3;
int boxColStart = col - col % 3;
for (int r = boxRowStart; r < boxRowStart + 3; r++)
{
for (int c = boxColStart; c < boxColStart + 3; c++)
{
if (pu[r, c] == num)
return false;
}
}
return true;
}
static bool SolveSudoku()
{
int row = -1;
int col = -1;
bool isEmpty = true;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (pu[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 (isSafe(row, col, num))
{
pu[row, col] = num;
if (SolveSudoku())
{
return true;
}
else
{
pu[row, col] = 0; // 回溯
}
}
}
return false;
}
}
}
01-01