数独

P1784 数独

搜素,以步数搜素条件,当setp>1时退出,方阵从0开始,第i行为step/9,第j列为step%9,

判断九宫格时,只要找左上角的位置即可,x+i,y+j,x=当前横坐标/3*3,y=当前纵坐标/3*3。

 

#include<iostream>
#define n 9
using namespace std;

int a[20][20];
bool flag;
bool x_use[20][20],y_use[20][20];

void in(int &x)
{
    int y=1;
    char c=getchar();x=0;
    while(c<'0'||c>'9')
    {
     if(c=='-')
     y=-1;
     c=getchar();    
    }
    while(c<='9'&&c>='0')x=x*10+c-'0',c=getchar();
    x*=y;
}

void init()
{
    for(int i=0;i<n;i++)
     for(int j=0;j<n;j++)
       {
           in(a[i][j]);
           if(a[i][j]!=0)
           {
           x_use[i][a[i][j]]=true;
           y_use[j][a[i][j]]=true;
        }
       }
}

bool test(int x,int y,int num)
{
    x=x/3*3;
    y=y/3*3;
    for(int i=0;i<3;i++)
      for(int j=0;j<3;j++)
        {
            if(a[i+x][j+y]==num)
            return false;
        }
    return true;
}


void out()
{
    for(int i=0;i<n;i++)
     {
         for(int j=0;j<n;j++)
         putchar(a[i][j]+'0'),putchar(' ');
         putchar('\n');
     }
      
}

void search(int step)
{
    if(step>80||flag)
    {        
    flag=true;
    return;    
    }
    if(a[step/9][step%9]!=0)
    search(step+1);
    else
    {
        for(int num=1;num<=9;num++)
        {
            if(!x_use[step/9][num]&&!y_use[step%9][num]&&test(step/9,step%9,num))
            {
                a[step/9][step%9]=num;
                x_use[step/9][num]=true;
                y_use[step%9][num]=true;
                search(step+1);
                if(flag)
                return;
                a[step/9][step%9]=0;
                x_use[step/9][num]=false;
                y_use[step%9][num]=false;
            }
        }
    }
}

int main()
{
    init();
    search(0);
    out();
    return 0;
}

 

posted @ 2017-09-10 10:57  WeiAR  阅读(174)  评论(0编辑  收藏  举报