我正在尝试制作数独检查函数,以查看输入的板是否有效。为此,我将生成一个板,并检查每个单独的行,列和9个方块的集合,以查看它们是否包含数字1-9。如果它们不包含该特定区域中的每个数字,则该函数将
return false;
现在,我专注于检查数独板的行。在查看编译版本时,我不想输入所有9行,所以我现在只关注一行。
程序检查该行是否包含全部9个数字。如果该行缺少其中一个数字(1-9),它将#include <iostream>
using namespace std;
const int DIMEN = 9;
bool is_valid(int []);
int main()
{
int board[DIMEN];
cout << "Enter values for array.\n";
for (int arraynumber = 0; arraynumber < DIMEN; arraynumber++)
{
cout << "\nArray [" << arraynumber << "]? ";
cin >> board[arraynumber];
}
bool valid = is_valid(board);
if (valid)
{
cout << "\nValid Board!\n";
}
else
{
cout << "\nInvalid Board!\n";
}
return 0;
}
bool is_valid(int isvalid[])
{
bool check_row = false;
//Checks to see if the row has all required numbers
bool check_number = false;
//Checks to see if the row contains a specific number in it
while (!(check_row))
//While the row doesn't yet have all required numbers in it
{
for (int number = 1; number <= DIMEN; number++)
// Goes through each # (1-9) to see if the row contains that #
{
while (!(check_number))
//While the row doesn't yet have the number in it
{
for (int i = 0; i < DIMEN; i++)
//Move across the row from column 0 to 8
{
if (isvalid[i] == number)
/* If the value for this specific element of the array
equals the number */
{
check_number = true;
//The row has the number in it
}
}
if (!(check_number))
/* If the number was not found in the row by the
end of the for loop */
{ return false;
//End the program saying the board is invalid
}
}
}
check_row = true;
}
return true;
}
到函数并显示&#34;无效的电路板!&#34;。
然而,该程序总是说它是一个有效的板,即使它缺少一些所需的数字。
到目前为止,这是我的代码的副本:
{{1}}
答案 0 :(得分:0)
当您开始检查新号码时,您永远不会将check_number
设置为假。
话虽如此,您的代码非常复杂且难以阅读。你可以这样做:
bool is_valid(int row[])
{
for(int number = 1; number <= 9; number++)
{
bool found = false;
for(int i = 0; i < DIMEN; i++) {
found = (row[i] == number);
if (found) break;
}
// We've looked at each spot in the row and not found number
// so we know the row isn't valid.
if (!found) return false;
}
// If we get here we must have found every number so the row is valid
return true;
}
答案 1 :(得分:0)
您的功能似乎不必要地复杂化。我不清楚它应该如何运作。这是一个应该有效的简化版本。
bool is_valid(int board[])
{
// start with board_state = {0, 0, 0, 0, 0, 0, 0, 0, 0}
// if the board is valid, we will end up with
// board_state = {1, 1, 1, 1, 1, 1, 1, 1, 1}
int board_state[DIMEN] = {0};
for ( int i = 0; i < DIMEN; ++i )
{
int n = board[i];
++board_state[n-1];
}
for ( int i = 0; i < DIMEN; ++i )
{
if ( board_state[i] != 1 )
{
return false;
}
}
return true;
}
答案 2 :(得分:0)
问题在于:
if (isvalid[i] == number)
/* If the value for this specific element of the array
equals the number */
{
check_number = true;
//The row has the number in it
}
一旦你做到了这一点,它将永远属于那个功能。
因此,如果您找到一个数字,则返回true!
注意:强> 在我做这个之前我做了数独游戏:
这将是一个更简单的实现:循环一次以设置该位,然后验证一次。