数独

花了半个小时搞了个数独。。

判断模拟

dfs回溯构造

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
#include<climits>
typedef long long LL;
using namespace std;
int RD(){
    int out = 0,flag = 1;char c = getchar();
    while(c < '0' || c >'9'){if(c == '-')flag = -1;c = getchar();}
    while(c >= '0' && c <= '9'){out = out * 10 + c - '0';c = getchar();}
    return flag * out;
    }
int map[19][19];

bool check(int x,int y){
	int k = map[x][y];
	for(int i = 1;i <= 9;i++){
		if(map[x][i] == k && i != y)return 0;
		}
	for(int i = 1;i <= 9;i++){
		if(map[i][y] == k && i != x)return 0;
		}
	int xx,yy;
	if(x >= 1 && x <= 3)xx = 1;
	else if (x >= 4 && x <= 6)xx = 4;
	else xx = 7;
	
	if(y >= 1 && y <= 3)yy = 1;
	else if (y >= 4 && y <= 6)yy = 4;
	else yy = 7;
	
	for(int i = xx;i <= xx + 2;i++)for(int j = yy;j <= yy + 2;j++){
		if(i == x && j == y)continue;
		if(map[i][j] == k)return 0;
		}
	return 1;
	}
void dfs(int x,int y,int cnt){
	if(cnt == 9 * 9){
		printf("\n\n\n\n");
		for(int i = 1;i <= 9;i++){
			if(i % 3 == 1)printf("\n");
			for(int j = 1;j <= 9;j++){
				if(j % 3 == 1)printf(" ");
				printf("%d ",map[i][j]);
				}
			printf("\n");
			}
		return ;
		}
	if(map[x][y] == 0){
		for(int i = 1;i <= 9;i++){
			map[x][y] = i;
			if(check(x,y)){
				if(y == 9)dfs(x + 1,1,cnt + 1);
				else dfs(x,y + 1,cnt + 1);
				}
			}
			map[x][y] = 0;
		}
	else{
		if(y == 9)dfs(x + 1,1,cnt + 1);
		else dfs(x,y + 1,cnt + 1);
		}
	}
int main(){
	for(int i = 1;i <= 9;i++)for(int j = 1;j <= 9;j++){
		map[i][j] = RD();
		}
	dfs(1,1,0);
	return 0;
	}
posted @ 2018-07-09 19:25  Tony_Double_Sky  阅读(202)  评论(0编辑  收藏  举报