这里的问题是,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();
}
}
}
答案 0 :(得分:1)
我在您的代码中发现了一些错误:
行:26 Control[] controlsFound = this.Controls.Find("Grid" + i.ToString(), false);
永远不会使用变量controlsFound
。在我看来,你应该在下面的foreach
循环中使用它。
我认为你的主要问题是调用FindUnassignedLocation();
它返回一个bool,但你没有检查它。应该是:
bool SolveSudoku()
{
if (FindUnassignedLocation())
{
for (int num = 1; num <= 9; num++)
{
if (NoConflicts(emptyRow, emptyCol, num))
{
Grid[emptyRow, emptyCol].Text = num.ToString();
return true;
}
}
}
return false;
}