2016年11月10日 星期四

TIOJ 1025 - 數獨問題

http://tioj.infor.org/problems/1025

就直接DFS下去就解決了



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<bits/stdc++.h>
using namespace std;

int s[10][10];
int ans;

void put(int x,int y){
    bool posi[10];
    bool bye=0;
    for(int i=x;i<=9;i++){
        for(int j=(i==x?y:1);j<=9;j++){
            if(s[i][j]==0){
                memset(posi,1,sizeof(posi));
                for(int ii=(i-1)/3*3+1,c=0;c<3;c++,ii++){
                    for(int jj=(j-1)/3*3+1,d=0;d<3;d++,jj++){
                        posi[s[ii][jj]]=0;
                    }
                }
                for(int k=1;k<=9;k++){
                    posi[s[i][k]]=0;
                    posi[s[k][j]]=0;
                }
                for(int k=1;k<=9;k++){
                    if(posi[k]){
                        s[i][j]=k;
                        put(i,j);
                    }
                }
                s[i][j]=0;
                bye=1;break;
            }
            if(i>=9 && j>=9){
                ans++;
                for(int ii=1;ii<=9;ii++){
                    for(int jj=1;jj<=9;jj++){
                        if(jj-1)cout<<" ";
                        cout<<s[ii][jj];
                    }
                    cout<<endl;
                }
                cout<<endl;
            }
        }
        if(bye)break;
    }
}

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    for(int i=1;i<=9;i++){
        for(int j=1;j<=9;j++){
            cin>>s[i][j];
        }
    }
    put(1,1);
    cout<<"there are a total of "<<ans<<" solution(s).";
}

沒有留言:

張貼留言