【发布时间】:2013-11-08 15:09:34
【问题描述】:
我想编写一个程序来解决 3*3 数独难题。我已经制作了一个程序,但它只适用于 50% 的问题,其余的它提供了 60% 的正确解决方案。对于每个可能的问题,我不知道如何在有限的步骤中解决它。我使用的技术是我正在搜索数组的每个单独元素并检查同一行和列中不存在哪些元素,然后将其放入该单元并移至下一个单元。但这并不是所有问题的解决方案。接下来想到的是,我们应该为一个单元写下每一个可能的数字,然后继续。但是我们将如何决定最终应该将哪个数字放入单元中。我只想知道如何编写一个适用于所有问题的解决方案。我希望你明白了。 我写的代码是
#include<iostream>
using namespace std;
int rowsearch(int l[9][9],int row,int num) // function to search a particular number from a row of array
{
int counter=0;
for (int c=0 ; c<9 ; c++)
{
if (l[row][c]==num)
counter=counter+1;
}
if (counter>0)
return 1;
else
return 0;
}
int colsearch(int l[9][9],int col,int num) // function to search a number from a column of an array
{
int counter=0;
for (int c=0 ; c<9 ; c++)
{
if (l[c][col]==num)
counter=counter+1;
}
if (counter>0)
return 1;
else
return 0;
}
int rowcolnotexist(int x[9][9],int row , int col) // to find a nuber which does not exists int a row and column
{
for (int c=1 ; c<=9 ; c++)
{
if ( rowsearch(x,row,c)!=1 && colsearch(x,col,c)!=1)
return c;
}
return 0;
}
int main()
{
int l[9][9]={};
// input of the list
for (int i=0 ; i<9 ; i++)
for (int j=0 ; j<9 ; j++)
{
cout<<"Enter "<<i+1<<"*"<<j+1<<"entry of the list(For not entering a number enter 0).";
cin>>l[i][j];
}
// operations
for (int i=0 ; i<9 ; i++)
{
for (int j=0 ; j<9 ; j++)
if (l[i][j]==0)
l[i][j]=rowcolnotexist(l,i,j);
}
// printing list
for (int i=0 ; i<9 ; i++)
{
for (int j=0 ; j<9 ; j++)
{
cout<<l[i][j];
if ((j+1)%3==0)
cout<<" ";
else
cout<<" ";
}
if ((i+1)%3==0)
cout<<"\n\n\n";
else
cout<<"\n\n";
}
return 0;
}
【问题讨论】:
-
-1 表示没有足够的空白
-
另外,您想为 3x3 拼图创建求解器,而您发布的代码是用于 9x9 拼图的。
-
请下次发布正确的缩进代码。我已经修复了它,但是您的代码中有错误!请检查您的代码!
-
它有 3*3 个盒子,每个盒子里还有 3*3 个元素,所以定义数组的总数变成 9*9
-
@TomKnapen 取决于您如何看待它。 3x3 数独游戏通常是指一个有 3x3 块的网格,每个块包含 3x3 个条目。
标签: c++