zoukankan      html  css  js  c++  java
  • Sudoku Solver POJ 2676 LightOJ 1397

      //题目链接:
    //http://poj.org/problem?id=2676
     //http://www.lightoj.com/volume_showproblem.php?problem=1397
    1
    #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <vector> 5 using namespace std; 6 7 int shudu[81], mark[81]; 8 bool flag; 9 10 struct node{ 11 int index; //记录空格的下标 12 int counts; //存放没有填的空格中可以填的数的个数 13 int a[10]; //存放没有填的空格中可以填哪些数 14 node(int i, int j) 15 { 16 index = i; 17 counts = j; 18 } 19 }; 20 21 vector<node> vec; 22 23 bool cmp(node v1, node v2){ 24 return v1.counts < v2.counts; 25 } 26 bool check(int n, int value){ 27 int hang = n / 9, lie = n % 9; 28 int i, j = hang * 9, k; 29 k = j + 9; 30 for(; j < k; ++j){ //检查行 31 if(shudu[j] == value) return false; 32 } 33 for(j = 0; j < 9; j++){ //检查列 34 if(shudu[lie+j*9] == value) return false; 35 } 36 hang /= 3; lie /= 3; 37 k = hang * 27 + lie * 3; 38 for(i = 0; i < 3; ++i) //检查小宫 39 for(j = 0; j < 3; ++j){ 40 if(shudu[k+i*9+j] == value) return false; 41 } 42 return true; 43 } 44 45 void display() 46 { 47 int i, j; 48 for(i = 0; i < 9; ++i){ 49 for(j = 0; j < 9; ++j) 50 printf("%c",shudu[i*9+j]+'0'); 51 puts(""); 52 } 53 } 54 55 void dfs(int k){ 56 if(flag) return; 57 if(k == 81){display(); flag = true; return;} 58 int n = vec[k].index; //搜索时从空格中可以填最少的个数,开始搜索 59 if(mark[n] == 1) dfs(k+1); 60 else{ 61 for(int j = 0; j < vec[k].counts; ++j){ 62 if(check(n, vec[k].a[j])){ 63 shudu[n] = vec[k].a[j]; mark[n] = -1; 64 dfs(k+1); 65 if(flag) return; 66 shudu[n] = 0; mark[n] = 0; 67 } 68 } 69 } 70 } 71 72 int main() 73 { 74 int T, i, j, k; char s[10]; 75 scanf("%d",&T); 76 getchar(); 77 for(int cas = 1; cas <= T; ++cas){ 78 cout<<"Case "<<cas<<":"<<endl; 79 for(i = 0; i < 81; ++i) mark[i] = 0; 80 for(i = 0; i < 9; ++i){ 81 scanf("%s",s); 82 getchar(); 83 for(j = 0; j < 9; ++j){ 84 shudu[i*9+j] = s[j] == '.' ? 0 : s[j] - '0'; 85 mark[i*9+j] = shudu[i*9+j] == 0 ? 0 : 1; 86 } 87 } 88 node tmp(0,0); 89 for(i = 0; i < 81; ++i){ 90 if(mark[i]) { 91 vec.push_back(node(i, 0)); 92 continue; 93 } 94 for(j = 1, k = 0; j < 10; ++j){ 95 if(check(i, j)) 96 tmp.a[k++] = j; 97 } 98 tmp.index = i; 99 tmp.counts = k; 100 vec.push_back(tmp); 101 } 102 sort(vec.begin(), vec.end(), cmp); //按counts(空格处可以填的个数)排序 103 flag = false; 104 dfs(0);//display(); 105 vec.clear(); 106 } 107 return 0; 108 }

    //LightOJ 数据很强,还未AC,知道怎么优化的麻烦告知一下,不胜感激!
  • 相关阅读:
    使用Graphics合成带二维码和头像的分享图(小程序分享、App分享)
    04_关键字的作用
    03_线程
    02_进程
    01_命名规范
    WebApi的创建,部署,Oauth身份认证(三)
    WebApi的创建,部署,Oauth身份认证(二)
    WebApi的创建,部署,Oauth身份认证(一)
    Prism.Interactivity 和 Prism.Modularity 介绍
    Prism BindableBase 和 Commands 的介绍
  • 原文地址:https://www.cnblogs.com/yaling/p/3191318.html
Copyright © 2011-2022 走看看