求解數獨(回溯法)
阿新 • • 發佈:2019-02-11
//數獨大概長這樣規則就是在空格中填寫1~9的數字,每一行,每一列,還有每個區域(如上不同顏色的3*3區域)都只能由1~9的一組數字組成也就是說同行,同類,同區域不能有相同的數字input:
5 * * * * 7 * * 6
* 6 * * * * 5 * 4
* 8 3 4 * * * * *
* * * 1 8 2 * 4 *
* * 1 * * * 9 * *
* 7 * 3 6 9 * * *
* * * * * 5 4 3 *
1 * 5 * * * * 9 *
7 * * 2 * * * * 1output:
5 1 4 9 2 7 3 8 6
9 6 7 8 3 1 5 2 4
2 8 3 4 5 6 1 7 9
6 5 9 1 8 2 7 4 3
3 2 1 5 7 4 9 6 8
4 7 8 3 6 9 2 1 5
8 9 2 6 1 5 4 3 7
1 3 5 7 4 8 6 9 2
7 4 6 2 9 3 8 5 1//此為唯一解不同的數獨解不一定唯一,也不一定有解
5 * * * * 7 * * 6
* 6 * * * * 5 * 4
* 8 3 4 * * * * *
* * * 1 8 2 * 4 *
* * 1 * * * 9 * *
* 7 * 3 6 9 * * *
* * * * * 5 4 3 *
1 * 5 * * * * 9 *
7 * * 2 * * * * 1output:
5 1 4 9 2 7 3 8 6
9 6 7 8 3 1 5 2 4
2 8 3 4 5 6 1 7 9
6 5 9 1 8 2 7 4 3
3 2 1 5 7 4 9 6 8
4 7 8 3 6 9 2 1 5
8 9 2 6 1 5 4 3 7
1 3 5 7 4 8 6 9 2
7 4 6 2 9 3 8 5 1//此為唯一解不同的數獨解不一定唯一,也不一定有解
#include<iostream> #include<stdio.h> #include<string> #include<sstream> #include<fstream> #include<vector> #include<iomanip> #include<stack> #include<list> #include<map> #include<set> #include<algorithm> using namespace std; int num=0; class point{ public: int x; int y; point(int a,int b){ x=a; y=b; } }; //檢查同行,同列,同區域內是否含有此數 bool check(int a[9][9],int i,int j,int k){ for(int x = 0;x<=8;x++){ if(a[x][j]==k){ return false; } } for(int x = 0;x<=8;x++){ if(a[i][x]==k){ return false; } } for(int p=(i/3)*3;p<(i/3)*3+3;p++){ for(int q=(j/3)*3;q<(j/3)*3+3;q++){ if(a[p][q]==k){ return false; } } } return true; } void out(int a[9][9]){ for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ cout<<a[i][j]<<" "; }cout<<endl; } } void solve(int a[9][9],vector<point>&v,int cur){ if(cur==v.size()){ out(a); cout<<endl; return; } for(int k=1;k<=9;k++){ if(check(a,v[cur].x,v[cur].y,k)){ a[v[cur].x][v[cur].y]=k; solve(a,v,cur+1); a[v[cur].x][v[cur].y]=0; } } return; } int main(){ int a[9][9]; vector<point>v;//記錄要填空的座標 for(int i=0;i<9;i++){ for(int j =0;j<9;j++){ cin>>a[i][j]; if(a[i][j]==0){ point p = point(i,j); v.push_back(p); } } } solve(a,v,0); return 0; }