C++解数读

来源:互联网 发布:林心如私生活糜烂 知乎 编辑:程序博客网 时间:2024/06/04 22:50
#include <iostream>using namespace std;int table[9][9]={{0,0,5,3,0,0,0,0,0},                {8,0,0,0,0,0,0,2,0},                {0,7,0,0,1,0,5,0,0},                {4,0,0,0,0,5,3,0,0},                {0,1,0,0,7,0,0,0,6},                {0,0,3,2,0,0,0,8,0},                {0,6,0,5,0,0,0,0,9},                {0,0,4,0,0,0,0,3,0},                {0,0,0,0,0,9,7,0,0}};bool test(int x,int y,int n){    for(int i=0;i<9;i++){            if(table[x][i]==n&&i!=y)                return false;            if(table[i][y]==n&&i!=x)                return false;        }    return true;}bool test2(int x,int y,int n){    for(int i=(x/3)*3;i<(x/3)*3+3;i++){        for(int j=(y/3)*3;j<(y/3)*3+3;j++){            if(table[i][j]==n){                if(i!=x&&j!=y)                return false;            }        }    }    return true;}bool search(int depth){    if(depth>=81)        return true;    else {        int x=depth/9;        int y=depth%9;        if(table[x][y]!=0)            return search(depth+1);        else{            for(int i=1;i<=9;i++){                table[x][y]=i;                if(test(x,y,i)&&test2(x,y,i)&&search(depth+1))                    return true;                else                    table[x][y]=0;            }            }        }        return false;    }int main(){    if(search(0)){        for(int i=0;i<9;i++){            for(int j=0;j<9;j++){                cout<<table[i][j]<<' ';            }            cout<<endl;        }    }    else        cout<<"no answer"<<endl;    return 0; }

0 0
原创粉丝点击