您的位置:首页 > 其它

数独(回溯)

2016-03-18 15:48 387 查看
#include <iostream>
using namespace std;
void search(int step);
bool mark(int step);
int ans=0;
int a[9][9];
int main()
{
int i,j;
for (i=0;i<9;i++)
for (j=0;j<9;j++)
cin>>a[i][j];
search(0);
return 0;
}

void search(int step)
{
int i,j;
int row=step/9;//行
int col=step%9;//列
if (step==81)
{
for (i=0;i<9;i++)
{
for (j=0;j<9;j++)
cout<<a[i][j];
cout<<endl;
}
}
else if (a[row][col]==0)
{
for (i=1;i<=9;i++)
{
a[row][col]=i;
if (mark(step)) search(step+1);
}
a[row][col]=0;//回溯
}
else search(step+1);
}

bool mark(int step)//判断数字
{
int i,j;
int row=step/9;
int col=step%9;
//判断行
for  (i=0;i<9;i++)
if (a[row][col]==a[row][i] && col!=i) return false;
//判断列
for (i=0;i<9;i++)
if (a[row][col]==a[i][col] && row!=i) return false;
//判断宫
int tempRow=row/3*3;//每个宫的行
int tempCol=col/3*3;//每个宫的列
for (i=tempRow;i<tempRow+3;i++)
for (j=tempCol;j<tempCol+3;j++)
if (a[row][col]==a[i][j] && row!=i && col!=j) return false;
//如果都符合,则返回真
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: