여기에서의 문제는 emptyRow와 emptyCol 변수가 실제로 작동하지 않는 경향이 있으며, 초기화시 실제로 값을 할당하더라도 항상 0 인 점입니다. 또한 여기에 실수를 할 수 있습니까?C# 스도쿠 솔버 변수 오작동
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();
}
}
}
StackOverflow는 버그가있는 코드를 디버깅하는 서비스가 아닙니다. 당신이해야 할 일은 ** 손으로 ** 쓰는 것 ** 당신의 프로그램이 작동하지 않는 간단한 경우를 위해 취해야 할 모든 단계들. 그런 다음 디버거에서 각각의 단계를 수행하십시오. 귀하가 직접 작성한 목록이 관찰 된 행동과 일치하지 않을 때, 그것이 바로 버그입니다. –
에릭의 충고는 여기에 절대적으로 자리 잡고 있습니다. 특히 자연스럽고 작고 관리 할 수있는 논리의 덩어리로 자연적으로 넘어갈 수있는 프로그램과 함께하십시오. 제안 된대로하면 프로그램 구조에 도움이되며 의도 한 동작이 마음에 들지 않으면 버그가 눈에.니다. – Chris
그래서 여기에 게시하기 전에 여러 번 했는데도 내 두 전역 변수 emptyRow 및 emptyCol이 할당 된 값을 사용하지 않고 그대로 유지되는 이유는 알 수 없습니다. – Kamilczak020