2676 Sudoku
虽然数据通过了,但是超时
这是一定的,那么多循环,发现一个规律,用数组可以省时间,而且少错误
我的代码——超时
#include "iostream" #include "string.h" #include "algorithm" using namespace std; int map[10][10]; int dir[9][2]={{1,1},{1,4},{1,7},{4,1},{4,4},{4,7},{7,1},{7,4},{7,7}}; bool chang(){ int set[10],set1[10],set2[10],i,j; memset(set,0,sizeof(set)); memset(set1,0,sizeof(set1)); memset(set2,0,sizeof(set2)); for(i=1;i<=9;i++){ int a=dir[i-1][0],b=dir[i-1][1]; for(j=1;j<=9;j++){ int ansa=a+(j-1)/3,ansb=b+(j-1)%3; if(map[i][j]==0)return 0; if(set1[map[i][j]]){return 0;} if(set[map[j][i]]){return 0;} if(set2[map[ansa][ansb]]){return 0;} set2[map[ansa][ansb]]=1; set1[map[i][j]]=1; set[map[j][i]]=1; } memset(set,0,sizeof(set)); memset(set1,0,sizeof(set1)); memset(set2,0,sizeof(set2)); } return 1; } bool check(int a,int b,int c){ int i,tema,temb; tema=(a-1)/3*3+1; temb=(b-1)/3*3+1; for(i=1;i<=9;i++){ int ansa=tema+(i-1)/3,ansb=temb+(i-1)%3; if(map[a][i]==c){return 0;} if(map[i][b]==c){return 0;} if(map[ansa][ansb]==c){return 0;} } return 1; } bool dfs(int tem){ int a=(tem-1)/9+1,b=tem%9,j; if(b==0)b=9; if(chang()&&tem==81)return 1; if(map[a][b]==0){ for(j=1;j<=9;j++){ if(check(a,b,j)){ map[a][b]=j; if(dfs(tem+1)){return 1;} map[a][b]=0; } } } else{ if(dfs(tem+1)){return 1;} } } int main(){ int ncase; char list[10]; cin>>ncase; while(ncase--){ int i,j; for(i=1;i<=9;i++){ cin>>list; for(j=0;j<9;j++){ map[i][j+1]=list[j]-'0'; } } if(dfs(1)) for(i=1;i<=9;i++){ for(j=1;j<=9;j++){ cout<<map[i][j]; }cout<<endl; } } }
人家的代码
#include <stdio.h> #include <string.h> #include <time.h> int rowok[9][10],colok[9][10],miyaok[9][10]; //用来记录行列宫有哪些数字 int sudoku[9][9],place[81][2],p,n; //place用来记录哪些位置需要填数 int search(int x, int y){ int i,j; if(p == n){ for(i = 0; i < 9; i++){ for(j = 0; j < 9; j++) printf("%d",sudoku[i][j]); puts(""); } return 1; } for(i = 1; i < 10; i++) if(!rowok[x][i] && !colok[y][i] && !miyaok[x/3*3+y/3][i]){ sudoku[x][y] = i; rowok[x][i] = colok[y][i] = miyaok[x/3*3+y/3][i] = 1; p++; if(search(place[p][0],place[p][1])) return 1; p--; sudoku[x][y] = 0; rowok[x][i] = colok[y][i] = miyaok[x/3*3+y/3][i] = 0; } return 0; } int main (void){ long t1; int i,j,T; // freopen("poj2676.in","r",stdin); scanf("%d",&T); while(T--){ p = 0; memset(rowok,0,sizeof(rowok)); memset(colok,0,sizeof(colok)); memset(miyaok,0,sizeof(miyaok)); for(i = 0; i < 9; i++){ for(j = 0; j < 9; j++){ scanf("%1d",&sudoku[i][j]); if(sudoku[i][j]){ rowok[i][sudoku[i][j]] = 1; colok[j][sudoku[i][j]] = 1; miyaok[i/3*3+j/3][sudoku[i][j]] = 1; } else{ place[p][0] = i; place[p][1] = j; p++; } } } n = p; p = 0; search(place[p][0],place[p][1]); } return 0; }