您的位置:首页 > 其它

poj 2676Sudoku(DFS+回溯)

2015-07-23 10:58 393 查看
[align=center]Sudoku[/align]

Time Limit: 2000MSMemory Limit: 65536K
Total Submissions: 15698Accepted: 7678Special 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

题目大意:数独游戏。将初始表示为0的数字全部填满,要求每行每列的数都不一样(1~9),并且每一个3*3的小块里面也是由1~9的数字填充。

所以可以把整个图里面的数字为0的位置都用一个数组存起来。然后在每一个空白的地方尝试去填写数字,然后每填一个数字就做好标记,表示在当前行、当前列、当前的小块里面已经放过这个数字了。

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
char map[15][15];
int rownum[15][15],colnum[15][15],blocknum[15][15];    //当前行、当前列、当前小块放置数字的标记。
struct pos{
int r,c;
pos(int rr,int cc):r(rr),c(cc){ }
};
vector<pos>blankpos;
int  getblocknum(int r,int c)          //获取当前数字所在小块的位置
{
int rr=r%3==0?r/3:(r/3+1);
int cc=c%3==0?c/3:(c/3+1);
return rr*3+cc;
}
void setflags(int i,int j,int num,int f)
{
rownum[i][num]=f;
colnum[j][num]=f;
blocknum[getblocknum(i,j)][num]=f;
}
bool isOk(int i,int j,int num)        //判断数字是否可行
{
return !rownum[i][num]&&!colnum[j][num]&&!blocknum[getblocknum(i,j)][num];
}
bool dfs(int n)
{
if(n<0)return true;
int i;
int r=blankpos
.r;
int c=blankpos
.c;
for(i=1;i<=9;i++)
{
if(isOk(r,c,i)){
map[r][c]=i;
setflags(r,c,i,1);
if(dfs(n-1))return true;
setflags(r,c,i,0);
}

}
return false;
}
int main()
{
int T,i,j,k;
scanf("%d",&T);
while(T--)
{
memset(rownum,0,sizeof(rownum));
memset(colnum,0,sizeof(colnum));
memset(blocknum,0,sizeof(blocknum));
blankpos.clear();
for(i=1;i<=9;i++)
for(j=1;j<=9;j++)
{
cin>>map[i][j];
map[i][j]=map[i][j]-'0';
if(map[i][j])setflags(i,j,map[i][j],1);
else blankpos.push_back(pos(i,j));     //把空的位置放入数组
}
if(dfs(blankpos.size()-1)){
for(i=1;i<=9;i++)
{
for(j=1;j<=9;j++)
cout<<char(map[i][j]+'0');
cout<<endl;
}
}
}
return 0;
 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: