Sudoku
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
Southeastern Europe 2005
题意:
一个标准的数独游戏,给你初始的情况,求出任意一组答案。
分析:
由于题目数据比较弱,给的空格处相对较少,所有可以直接进行DFS搜索。每次判断出行,列,3*3的小格子内没有出现的数,然后进行枚举搜索即可。
正搜1672ms — 倒搜16ms
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
char omap[10][10];
int mmap[10][10];
int flag;
int judge(int i,int j,int k)
{
//行
for(int t=1;t<=9;t++)
{
if(mmap[i][t] == k) return 0;
}
//列
for(int t=1;t<=9;t++)
{
if(mmap[t][j] == k) return 0;
}
//3*3的格子
int x,y;
if(i <= 3) x = 1;
else if(i > 3 && i <7) x = 4;
else x = 7;
if(j <= 3) y = 1;
else if(j >3 && j <7) y = 4;
else y = 7;
for(int xx=0;xx<3;xx++)
{
for(int yy =0;yy<3;yy++)
{
if(mmap[x+xx][y+yy] == k) return 0;
}
}
return 1;
}
void dfs(int dep)
{
if(dep <=0)
{
flag = 1;
return ;
}
int i = (dep-1)/9+1;
int j = dep-(i-1)*9;
if(mmap[i][j] != 0) dfs(dep-1);
else
{
for(int k=1;k<=9;k++)
{
if(judge(i,j,k)==1)
{
mmap[i][j] = k;
dfs(dep-1);
if(flag) return;
mmap[i][j] = 0;
}
}
}
}
int main()
{
int t;
scanf("%d\n",&t);
while(t--)
{
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++)
{
scanf("%c",&omap[i][j]);
mmap[i][j] = omap[i][j]-'0';
}
getchar();
}
flag = 0;
dfs(81);
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++)
{
printf("%d",mmap[i][j]);
}
printf("\n");
}
}
return 0;
}