题干:

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

 

解题报告:

   直接搜索dfs。注意那个判断是否在同一个分块中的那个a数组,可以直接手写,也可以找规律推出一个公式。

AC代码:(1032ms)

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<map>
#include<cstring>
#define m_p make_pair
using namespace std;
int maze[10][10];
bool c[10][10],r[10][10],a[10][10];//c列   r行  a分块 
typedef pair<int,int> pr;
map<pr,int> mp;
int flag;
void dfs(int x,int y) {
	if(x == 10) {
		flag = 1;
		return ;
	}
	if(flag) return ;	
	if(maze[x][y]!=0) {
		if(y!=9) dfs(x,y+1);
		else dfs(x+1,1);
		return ;
	}
	//下面都是maze[i][j]==0的情况了。 
	for(int i = 1; i<=9; i++) {
		if(c[y][i] || r[x][i] || a[mp[m_p(x,y)]][i]) continue;
		c[y][i] = r[x][i] = a[mp[m_p(x,y)]][i] = 1;
		maze[x][y] = i;
		if(y != 9) dfs(x,y+1);
		else dfs(x+1,1);
		if(flag) return ;
		c[y][i] = r[x][i] = a[mp[m_p(x,y)]][i] = 0;
		maze[x][y]=0;
	}
}
int main()
{
	
	int t;
	cin>>t;
	//打表 
	for(int i = 1; i<=9; i++) {
		for(int j = 1; j<=9; j++) {
			mp[m_p(i,j)] = 3*((i-1)/3)+(j-1)/3 + 1;//从1~9编号。 
		}
	}
	while(t--) {
		flag=0;
		memset(c,0,sizeof c);memset(r,0,sizeof r);memset(a,0,sizeof a);
		for(int i = 1; i<=9; i++) {
			for(int j = 1; j<=9; j++) {
				scanf("%1d",&maze[i][j]);
				c[j][maze[i][j]] = 1;
				r[i][maze[i][j]] = 1;
				a[mp[m_p(i,j)]][maze[i][j]] = 1;
			}
		}
		dfs(1,1); 
		for(int i = 1; i<=9; i++) {
			for(int j = 1; j<=9; j++) {
				printf("%d",maze[i][j]);
			}
			printf("\n");
		}
	}
	return 0 ;
 }