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
Output
Sample Input
1 103000509 002109400 000704000 300502006 060000050 700803004 000401000 009205800 804000107
Sample Output
143628579 572139468 986754231 391542786 468917352 725863914 237481695 619275843 854396127
依旧是经典的数独问题,上次我写过一个4*4的,这次是9*9。
这题里学到一个技巧分块方面的技巧(可怜我还是一点一点判断的)
这个问题太经典了,就不多说了,附代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int M = 12;
char st[M][M];
int map[M][M];
int col[M][M];
int row[M][M];
int bl[M][M];
int f=0;
int dfs(int x,int y){
if(y==10)
return 1;
f=0;
if(map[x][y]){
if(x<9) f=dfs(x+1,y);
else f=dfs(1,y+1);
if(f) return 1;
else return 0;
}
else{
int k=3*((x-1)/3)+(y-1)/3+1;
for(int i=1;i<=9;i++){
if(!col[y][i]&&!row[x][i]&&!bl[k][i]){
map[x][y]=i;
col[y][i]=1;
row[x][i]=1;
bl[k][i]=1;
if(x<9) f=dfs(x+1,y);
else f=dfs(1,y+1);
if(f) return 1;
else{
map[x][y]=0;
row[x][i]=0;
col[y][i]=0;
bl[k][i]=0;
}
}
}
}
return 0;
}
int main(){
int t;
cin>>t;
while(t--){
memset(row,false,sizeof(row));
memset(col,false,sizeof(col));
memset(bl,false,sizeof(bl));
f=0;
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++){
cin>>st[i][j];
map[i][j]=st[i][j]-‘0‘;
if(map[i][j])
{
int k=3*((i-1)/3)+(j-1)/3+1; //分块技巧
row[i][ map[i][j] ]=1;
col[j][ map[i][j] ]=1;
bl[k][ map[i][j] ]=1;
}
}
}
dfs(1,1);
for(int i=1;i<=9;i++){
for(int k=1;k<=9;k++){
cout<<map[i][k];
}
cout<<endl;
}
}
return 0;
}
原文:http://www.cnblogs.com/zmin/p/7324473.html