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.
![](https://i-blog.csdnimg.cn/blog_migrate/56e7e6182093bbca488d6c73ba833af6.jpeg)
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.
题意:如题目所述,给你一个9*9的大方格,有的方格里已经有数字了,将整个大方格填满数字,要求每一行有9个不同的数字,即1~9,每一列也是如此,每一个小3*3的方格也是如此。
Sample Input
1 103000509 002109400 000704000 300502006 060000050 700803004 000401000 009205800 804000107
Sample Output
143628579 572139468 986754231 391542786 468917352 725863914 237481695 619275843 854396127
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
#define MAX 0x3f3f3f3f
using namespace std;
char mmap[10][10]; //存储添数字的方格
bool x[10][10],y[10][10],sd[10][10]; //标记行出现的数字,标记列出现的数字,标记小3*3方格的数字
int getlen(int a,int b) //获得此时单格子所在的小3*3方格编号
{
return ((a+2)/3-1)*3+(b+2)/3;
}
bool DFS(int xx,int yy) //传进来横纵坐标
{
if(xx==9&&yy==9) //如果已全部遍历完则返回true
return true;
xx=(yy==9)?xx+1:xx; //进行换行
yy=(yy==9)?1:yy+1; //进行换列
if(mmap[xx][yy]!='0') //如果此坐标方格已经有数字则继续递归下一个方格
return DFS(xx,yy);
for(int i=1; i<=9; i++) //开始遍历1~9数字
{
if(x[xx][i]||y[yy][i]||sd[getlen(xx,yy)][i]) //如果在行或列或小3*3方格中出现过数字i,则接着遍历数字
continue;
x[xx][i]=y[yy][i]=sd[getlen(xx,yy)][i]=true; //标记数字i
mmap[xx][yy]='0'+i; //将坐标为xx,yy的方格添上数字i
if(DFS(xx,yy)) //如果已经填满了所有的方格则直接返回
return true;
x[xx][i]=y[yy][i]=sd[getlen(xx,yy)][i]=false; //取消标记
}
mmap[xx][yy]='0'; //恢复为0
return false;
}
int main()
{
//freopen("lalala.text","r",stdin);
int t,i,j;
scanf("%d",&t);
while(t--)
{
memset(mmap,0,sizeof(mmap));
memset(x,0,sizeof(x));
memset(y,0,sizeof(y));
memset(sd,0,sizeof(sd));
for(i=1; i<=9; i++)
{
scanf("%s",mmap[i]+1);
for(j=1; j<=9; j++)
{
if(mmap[i][j]!='0')
{
x[i][mmap[i][j]-'0']=true;
y[j][mmap[i][j]-'0']=true;
sd[getlen(i,j)][mmap[i][j]-'0']=true;
}
}
}
DFS(1,0); //将填满数字的方格输出
for(i=1; i<=9; i++)
printf("%s\n",mmap[i]+1);
}
return 0;
}<strong>
</strong>