这里的问题是,emptyRow 和emptyCol 变量在某种程度上不倾向于工作并且总是等于0,即使我在初始化时实际上为它们赋值!同样,您是否看到我在这里可能犯的任何错误?
这是代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Declaration of Fields, used to conjoin methods
RichTextBox[,] Grid = new RichTextBox[9, 9];
int emptyRow, emptyCol;
private void Form1_Load(object sender, EventArgs e)
{
// Creating a grid of Textboxes, for further use in a solving algorithm
// and setting alignment to center for all boxes
int i = 0;
for (int row = 0; row < 9; row++)
{
for (int col = 0; col < 9; col++)
{
i++;
Control[] foundControls = this.Controls.Find("Grid" + i.ToString(), false);
foreach (Control currentControl in foundControls)
{
if (currentControl.GetType() == typeof(RichTextBox))
{
RichTextBox currentRichTextBox = (RichTextBox)currentControl;
Grid[row, col] = currentRichTextBox;
currentRichTextBox.SelectionAlignment = HorizontalAlignment.Center;
}
}
}
}
}
bool SolveSudoku()
{
FindUnassignedLocation();
for (int num = 1; num <= 9; num++)
{
if (NoConflicts(emptyRow, emptyCol, num))
{
Grid[emptyRow, emptyCol].Text = num.ToString();
return true;
}
}
return false;
}
// Method to determine wether any fields are empty and if so, returning the first found
bool FindUnassignedLocation()
{
for (int row = 0; row < 9; row++)
{
for (int col = 0; col < 9; col++)
{
if (Grid[row, col].Text == "")
{
emptyRow = row;
emptyCol = col;
return true;
}
}
}
return false;
}
// Check if there are any conflicts in row or col or box
bool NoConflicts(int row, int col, int num)
{
return !UsedInRow(row, num) && !UsedInCol(col, num) &&
!UsedInBox(row - row % 3, col - col % 3, num);
}
// Check if there are any conflicts in row
bool UsedInRow(int row, int num)
{
for (int col = 0; col < 9; col++)
{
if (Grid[row, col].Text == num.ToString())
{
return true;
}
}
return false;
}
// Check if there are any conflicts in column
bool UsedInCol(int col, int num)
{
for (int row = 0; row < 9; row++)
{
if (Grid[row, col].Text == num.ToString())
{
return true;
}
}
return false;
// Check if there are any conflicts in box
}
bool UsedInBox(int boxStartRow, int boxStartCol, int num)
{
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++)
{
if (Grid[row + boxStartRow, col + boxStartCol].Text == num.ToString())
{
return true;
}
}
}
return false;
}
private void button1_Click(object sender, EventArgs e)
{
SolveSudoku();
}
}
}