您的位置:首页 > 其它

poj 2676 -- Sudoku

2014-08-06 19:39 274 查看
Sudoku

Time Limit: 2000MSMemory Limit: 65536K
Total Submissions: 13723Accepted: 6791Special 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.

/*======================================================================
*           Author :   kevin
*         Filename :   suduku.cpp
*       Creat time :   2014-08-06 15:51
*      Description :
========================================================================*/
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
#define clr(a,b) memset(a,b,sizeof(a))
#define M 20
using namespace std;
int s[M][M],row[M][M],col[M][M];
/*-------判断是否有3×3格子里是否有b-------*/
bool judge(int x,int y,int b)
{
int i,j;
for(i = (x-1)/3*3+1; i <= (x-1)/3*3+3; i++){
for(j = (y-1)/3*3+1; j <= (y-1)/3*3+3; j++){
if(s[i][j] == b) return false;
}
}
return true;
}
/*----------------end----------------*/
bool DFS(int x,int y) // x代表列,y代表行
{
if(x == 9 && y == 0){
return true;
}
if(s[y][x]){
if(x > 1){
if(DFS(x-1,y))
return true;
}
if(x == 1){
if(DFS(9,y-1))
return true;
}
}
else{
for(int i = 1; i <= 9; i++){      //枚举1到9
if(!row[y][i] && !col[x][i]){ //当前行当前列是否有i
if(judge(y,x,i)){         //判断能否放在3×3方格里
row[y][i] = 1; col[x][i] = 1;
s[y][x] = i;
if(x > 1){
if(DFS(x-1,y)){
return true;
}
}
if(x == 1){
if(DFS(9,y-1)){
return true;
}
}
row[y][i] = 0; col[x][i] = 0;
s[y][x] = 0;
}
}
}
}
return false;
}
int main(int argc,char *argv[])
{
int n;
scanf("%d",&n);
getchar();
while(n--){
clr(s,0);
clr(row,0);
clr(col,0);
char c;
for(int i  = 1; i <= 9; i++){
for(int j = 1; j <= 9; j++){
scanf("%c",&c);
s[i][j] = c-'0';
row[i][s[i][j]] = 1;   //标记行里出现的数
col[j][s[i][j]] = 1;   //标记列里出现的数
}
getchar();
}
DFS(9,9);          //倒着搜
for(int i = 1; i <= 9; i++){
for(int j = 1; j <= 9; j++){
printf("%d",s[i][j]);
}
printf("\n");
}
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: