码迷,mamicode.com
首页 > 其他好文 > 详细

九宫格练习 9*9数独游戏

时间:2015-05-19 19:12:05      阅读:631      评论:0      收藏:0      [点我收藏+]

标签:九宫格练习   99数独游戏   

#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数独游戏

标签:九宫格练习   99数独游戏   

原文地址:http://blog.csdn.net/timelimite/article/details/45846771

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!