关闭

poj 2676 Sudoku (基础DFS)

标签: pojdfs
592人阅读 评论(0) 收藏 举报
分类:


Sudoku
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 15456   Accepted: 7574   Special Judge

Description

Sudoku is a very simple task. A square table with 9 rows and 9 columns is divided to 9 smaller squares 3x3 as shown on the Figure. In some of the cells are written decimal digits from 1 to 9. The other cells are empty. The goal is to fill the empty cells with decimal digits from 1 to 9, one digit per cell, in such way that in each row, in each column and in each marked 3x3 subsquare, all the digits from 1 to 9 to appear. Write a program to solve a given Sudoku-task. 

Input

The input data will start with the number of the test cases. For each test case, 9 lines follow, corresponding to the rows of the table. On each line a string of exactly 9 decimal digits is given, corresponding to the cells in this line. If a cell is empty it is represented by 0.

Output

For each test case your program should print the solution in the same format as the input data. The empty cells have to be filled according to the rules. If solutions is not unique, then the program may print any one of them.

Sample Input

1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107

Sample Output

143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127

Source



题目链接:http://poj.org/problem?id=2676


题目大意:数独游戏。用9个数字填满一个有9*9个格子的棋盘,有的格子里已经填有数字,有的格子是空白格子,标记为0,要求在空白格子中填入数字,保证每行每列每个小九宫格里1-9个数字都出现。


解题思路:枚举9个数字,DFS搜索满足填入数字的情况,经典搜索题。


代码如下:

#include <cstdio>
#include <cstring>
int a[10][10];
char s[10][10];
bool p;
bool ok(int k,int x,int y)  //判断数字k是否满足条件
{
	for(int i=0;i<9;i++)    //保证每行不出现重复数字
		if(a[x][i]==k)
			return false;   //保证每列不出现重复数字
	for(int i=0;i<9;i++)
		if(a[i][y]==k)
			return false;
	x=x-x%3,y=y-y%3;
	for(int i=x;i<x+3;i++)  //保证每个小九宫格里不出现重复数字
		for(int j=y;j<y+3;j++)
		{
			if(a[i][j]==k)
				return false;
		}
	return true;
}
void dfs(int x,int y)   //x,y是当前格子的横纵坐标
{
	if(p||x==9)         //x为9时说明格子已填满,p标记搜索成功,返回
	{
		p=true;
		return;
	}
	while(a[x][y])      //当格子里有数字时改变坐标直道得到空格子
	{
		if(y==8)
		{
			x++;
			y=0;
		}
		else
		y++;
		if(x==9)
		{
			p=true;
			return;
		}
	} 
	for(int k=1;k<=9;k++)   //枚举九个数字,判断这些数字是否能填入当前格子
	{
		if(ok(k,x,y))
		{
			a[x][y]=k;
			if(y==8)
				dfs(x+1,0);
			else
				dfs(x,y+1);
			if(p)
				return;
			a[x][y]=0;
		}
	}
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		p=false;
		for(int i=0;i<9;i++)
		{
			scanf("%s",s[i]);
			for(int j=0;j<9;j++)
				a[i][j]=s[i][j]-'0';
		}
		dfs(0,0);
		for(int i=0;i<9;i++)
		{
			for(int j=0;j<9;j++)
				printf("%d",a[i][j]);
			printf("\n");
		}
	}
	return 0;
}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:49463次
    • 积分:1991
    • 等级:
    • 排名:第19612名
    • 原创:160篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条