1. 程式人生 > >TOJ 3287 Sudoku 9*9數獨 dfs

TOJ 3287 Sudoku 9*9數獨 dfs

描述

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. 

輸入

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.

輸出

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.

樣例輸入

1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107

樣例輸出

143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127

題目來源

Southeastern Europe 2005

數獨規則:橫向,縱向,3*3的小方格里,1-9各出現一次。

題意:0的位置填補數,輸出一種填法。3*(i/3)+j/3是計算在第幾個小方格里。

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<vector>
using namespace std;
#define inf 0x3f3f3f3f
#define LL long long
int a[20][20],flag;
int r[20][20],l[20][20],s[20][20];//r行 l列 s小方陣 
void dfs(int i,int j)
{
	if(i==9&&j==0)
	flag=1;	
	else
	{
		if(a[i][j]!=0)
		{
			if(j<8)
			dfs(i,j+1);
			else
			dfs(i+1,0);
		}
		else
		{
			for(int k=1;k<=9;k++)
			{
				if(!r[i][k]&&!l[j][k]&&!s[3*(i/3)+j/3][k])
				{
					a[i][j]=k;
					r[i][k]=1;
					l[j][k]=1;
					s[3*(i/3)+j/3][k]=1;
					if(j<8)
					dfs(i,j+1);
					else
					dfs(i+1,0);
					if(flag)return;
					//回溯重置 
					a[i][j]=0;
					r[i][k]=0;
					l[j][k]=0;
					s[3*(i/3)+j/3][k]=0;
				}
			}
		}
	}
}
int main()
{
	int t,i,j;
	scanf("%d",&t);
	while(t--)
	{
		memset(r,0,sizeof r);
		memset(l,0,sizeof l);		
		memset(s,0,sizeof s);
		for(i=0;i<9;i++)
		{
			for(j=0;j<9;j++)
			{
				scanf("%1d",&a[i][j]);
				if(a[i][j])
				{
					r[i][a[i][j]]=1;
					l[j][a[i][j]]=1;
					s[3*(i/3)+j/3][a[i][j]]=1;
				}
			}
		}
		flag=0;
		dfs(0,0);
		for(i=0;i<9;i++)
		{
			for(j=0;j<9;j++)
			{
				printf("%d",a[i][j]);
			}
			printf("\n");
		}
	}
}