做这题主要学会了如何DFS一个九宫格,举一反三,以后遇到这种题目可别再不会了,一开始我想的是用八皇后的方法,发现不行啊,如何判断这行这列有没有用这个数字呢。最后的办法是建立数组row[][],col[][],grid[][],还有一个是大格和小九宫格的换算公式:3*(i/3)+j/3;
Sudoku
Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 9748 | Accepted: 4827 | 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
Southeastern Europe 2005
#include <iostream>
#include <fstream>
#include <cstdio>
using namespace std;
int n;
int map[10][10];
bool row[10][10]; //记录每行的数字是否可行
bool col[10][10]; //记录没列的数字是否可行
bool grid[10][10]; //记录每个九宫格的数字是否可行
void getmap()
{
char s[10];
for(int i=0 ;i<9 ;i++)
{
getchar();
scanf("%s",s);
for(int j=0; j<9; j++)
{
map[i][j]=s[j]-'0';
if(map[i][j]!=0)
{
int num=map[i][j];
int k=3*(i/3)+j/3; // 这个公式很关键。这是求每个点对应的九宫格
row[i][num]=true;
col[j][num]=true;
grid[k][num]=true;
}
}
}
}
bool dfs(int i,int j)
{
bool flag=false;
if(i==9) return true;
if(map[i][j])
{
if(j==8)
{
flag=dfs(i+1,0);
}
else
{
flag=dfs(i,j+1);
}
if(flag) //在这回溯,但不改变map的值,只起到一个传递的作用
return true;
else
return false;
}
else
{
int k=3*(i/3)+j/3;
for(int x=1; x<=9; x++)
{
if(!row[i][x] && !col[j][x] && !grid[k][x])
{
map[i][j]=x;
row[i][x]=true;
col[j][x]=true;
grid[k][x]=true;
if(j==8)
{
flag=dfs(i+1,0);
}
else
{
flag=dfs(i,j+1);
}
if(!flag) //这也是一个回溯
{
map[i][j]=0;
row[i][x]=false;
col[j][x]=false;
grid[k][x]=false;
}
else
{
return true;
}
}//if
}//for
}
return false;
}
void output()
{
for(int i=0; i<9; i++)
{
for(int j=0; j<9; j++)
{
printf("%d",map[i][j]);
}
printf("\n");
}
}
int main()
{
freopen("acm.txt","r",stdin);
scanf("%d",&n);
while(n--)
{
memset(row,false,sizeof(row));
memset(col,false,sizeof(col));
memset(grid,false,sizeof(grid));
getmap();
dfs(0,0);
output();
}
return 0;
}