#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#define ceil(a,b) (((a)+(b)-1)/(b))
#define endl '\n'
#define gcd __gcd
#define highBit(x) (1ULL<<(63-__builtin_clzll(x)))
#define popCount __builtin_popcountll
typedef long long ll;
using namespace std;
const int MOD = 1000000007;
const long double PI = acos(-1.L);
template<class T> inline T lcm(const T& a, const T& b) { return a/gcd(a, b)*b; }
template<class T> inline T lowBit(const T& x) { return x&-x; }
template<class T> inline T maximize(T& a, const T& b) { return a=a<b?b:a; }
template<class T> inline T minimize(T& a, const T& b) { return a=a<b?a:b; }
const int maxn = 9;
int a[maxn][maxn];
struct node {
int x;
int y;
int v;
}space[maxn * maxn];
int cnt = 0;
void print(){
for (int i=0;i<maxn;i++){
for (int j=0;j<maxn;j++){
printf("%d ",a[i][j]);
}
puts("");
}
}
int flag = 0;
bool judge(int x,int y,int num){
a[x][y] = num;
for (int i=0;i<maxn;i++)
if (a[i][y]==a[x][y]&&a[i][y]!=0&&i!=x)
return false;
for (int i=0;i<maxn;i++)
if (a[x][i]==a[x][y]&&a[x][i]!=0&&i!=y)
return false;
for (int i=0;i<3;i++)
for (int j=0;j<3;j++){
int tx = x / 3 * 3 + i;
int ty = y / 3 * 3 + j;
if (tx==x&&ty==y)
continue;
if (a[tx][ty]==a[x][y])
return false;
}
a[x][y] = 0;
return true;
}
void dfs(int x,int y,int now){
if (now == cnt){
//cout<< now << endl;
print();
flag = 1;//找到一组解就return
return ;
}
if (flag)
return ;
// printf("%d\n",now);
// printf("now = %d\n",now);
// print();
// printf("----------------\n");
for (int i=1;i<=9;i++){
if (!flag&&judge(x,y,i)){
a[x][y] = i;
dfs(space[now+1].x,space[now+1].y,now+1);
a[x][y] = 0;
}
}
a[x][y] = 0;//所有的走走完了,这步还是不行,回溯这一步
}
int main() {
freopen("G:\\Code\\1.txt","r",stdin);
for (int i=0;i<maxn;i++)
for (int j=0;j<maxn;j++)
scanf("%d",&a[i][j]);
for (int i=0;i<maxn;i++)
for (int j=0;j<maxn;j++)
if (a[i][j] == 0){
space[cnt].x = i;
space[cnt].y = j;
space[cnt++].v = 0;
}
//cout << cnt << endl;
flag = 0;
for (int i=1;i<=9;i++){
if (judge(space[0].x,space[0].y,i)){
a[space[0].x][space[0].y] = i;
dfs(space[1].x,space[1].y,1);
a[space[0].x][space[0].y] = 0;
}
}
//printf("now = %d\n",now);
//print();
//printf("----------------\n");
return 0;
}
九宫格练习 9*9数独游戏
原文作者:九宫格问题
原文地址: https://blog.csdn.net/TIMELIMITE/article/details/45846771
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/TIMELIMITE/article/details/45846771
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。