歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言遞歸解決數獨

C語言遞歸解決數獨

日期:2017/3/1 10:10:20   编辑:Linux編程

運行程序,依次輸入數獨中的81個數,數獨中沒有數字的地方輸入0,感覺需要輸入那麼多數太麻煩了,請大家指導如何改的簡單一點。

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #define DEBUG
  4. int shukudo[9][9];
  5. typedef struct shudo{
  6. int x;
  7. int y;
  8. struct shudo * next;
  9. }shukudo_ptr;
  10. int count = 0;
  11. void display_shukudo();
  12. int check_right(shukudo_ptr*,int);
  13. void solution(shukudo_ptr *empty_ptr)
  14. {
  15. if(!empty_ptr)
  16. {
  17. display_shukudo();
  18. return;
  19. }
  20. for(int i = 1; i < 10; ++i)
  21. {
  22. if(check_right(empty_ptr,i))
  23. {
  24. shukudo[empty_ptr->x][empty_ptr->y] = i;
  25. solution(empty_ptr->next);
  26. }
  27. shukudo[empty_ptr->x][empty_ptr->y] = 0;
  28. }
  29. }
  30. int check_right(shukudo_ptr *empty_ptr,int n)
  31. {
  32. for(int i = 0; i < 9; ++i)
  33. {
  34. if(shukudo[empty_ptr->x][i] == n)
  35. {
  36. return 0;
  37. }
  38. }
  39. for(int i = 0; i < 9; ++i)
  40. {
  41. if(shukudo[i][empty_ptr->y] == n)
  42. {
  43. return 0;
  44. }
  45. }
  46. int start_x = empty_ptr->x / 3 * 3;
  47. int start_y = empty_ptr->y / 3 * 3;
  48. for(int i = start_x; i < start_x + 3; ++i)
  49. {
  50. for(int j = start_y; j < start_y + 3; ++j)
  51. {
  52. if(shukudo[i][j] == n)
  53. {
  54. return 0;
  55. }
  56. }
  57. }
  58. return 1;
  59. }
  60. void display_shukudo()
  61. {
  62. ++count;
  63. printf("solution %d\n",count);
  64. for(int i = 0; i < 9; ++i)
  65. {
  66. for(int j = 0; j < 9; ++j)
  67. {
  68. printf("%d ",shukudo[i][j]);
  69. }
  70. printf("\n");
  71. }
  72. printf("\n\n");
  73. }
  74. int main(void)
  75. {
  76. shukudo_ptr *empty_ptr = NULL;
  77. shukudo_ptr *operate = NULL;
  78. shukudo_ptr *last = NULL;
  79. for(int i = 0; i < 9; ++i)
  80. {
  81. for(int j = 0; j < 9; ++j)
  82. {
  83. printf("(%d,%d): ",i,j);
  84. scanf("%d",&shukudo[i][j]);
  85. if(shukudo[i][j] == 0)
  86. {
  87. operate = (shukudo_ptr*)malloc(sizeof(shukudo_ptr));
  88. operate->x = i;
  89. operate->y = j;
  90. operate->next = NULL;
  91. if(!empty_ptr)
  92. {
  93. empty_ptr = operate;
  94. last = empty_ptr;
  95. }
  96. else
  97. {
  98. last->next = operate;
  99. last = operate;
  100. }
  101. }
  102. }
  103. }
  104. solution(empty_ptr);
  105. while(empty_ptr)
  106. {
  107. operate = empty_ptr;
  108. empty_ptr = empty_ptr -> next;
  109. free(operate);
  110. }
  111. return 0;
  112. }
Copyright © Linux教程網 All Rights Reserved