indongsaeng

Sudoko C++

Oct 6th, 2013
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <fstream>
  4. #include <cmath>
  5.  
  6. using namespace std;
  7. bool sor(int s,int o,int n);
  8. bool oszlop(int s,int o,int n);
  9. bool negyzet(int s,int o,int n);
  10.  
  11. int a[9][9];
  12. int main()
  13. {
  14. int un=0,s,o,tmp;
  15. bool b=1;
  16. char c[20];
  17. cout << "write it manually (k) or read from file (f)? ";
  18. cin >> c[0];
  19. if(c[0]=='f')
  20. {
  21. cout << "give the sudoku filename: ";
  22. cin >> c;
  23. cout << endl;
  24. ifstream in(c);
  25. for(int i=0;i<9;i++)
  26. {
  27. for(int j=0;j<9;j++)
  28. {
  29. in >> a[i][j];
  30. if(!a[i][j])
  31. un++;
  32. }
  33. }
  34. in.close();
  35. }else if(c[0]=='k')
  36. {
  37. for(int i=0;i<9;i++)
  38. for(int j=0;j<9;j++)
  39. {
  40. do{
  41. cout << "Please enter " << i+1 << ". row " << j+1 << ". number: ";
  42. cin >> a[i][j];
  43. }while(a[i][j]<=0 && a[i][j]>10);
  44. if(a[i][j]==0)
  45. un++;
  46. }
  47. }else
  48. {
  49. cout << "exiting..." << endl;
  50. return 0;
  51. }
  52. while(un && b)
  53. {
  54. b=0;
  55. for(int i=0;i<9;i++)
  56. {
  57. for(int j=0;j<9;j++)
  58. {
  59. if(a[i][j]!=0)
  60. continue;
  61. tmp=0;
  62. for(int x=1;x<10;x++)
  63. {
  64. if(sor(i,j,x) && oszlop(i,j,x) && negyzet(i,j,x))
  65. {
  66. if(tmp==0)
  67. tmp=x;
  68. else{
  69. tmp=0;
  70. break;
  71. }
  72. }
  73. }
  74. if(tmp!=0)
  75. {
  76. a[i][j]=tmp;
  77. b=1;
  78. un--;
  79. }
  80. }
  81. }
  82. }
  83. if(!b)
  84. cout << "It cannot be solved" << endl;
  85. else if(!un)
  86. cout << "solved" << endl;
  87. cout << endl;
  88. for(int i=0;i<9;i++)
  89. {
  90. for(int j=0;j<9;j++)
  91. {
  92. cout << a[i][j] << " ";
  93. }
  94. cout << endl;
  95. }
  96. cout << endl;
  97. }
  98.  
  99. bool sor(int s,int o,int n)
  100. {
  101. for(int g=0;g<9;g++)
  102. {
  103.  
  104. if(a[s][g]==n)
  105. {
  106. return 0;
  107. }
  108. }
  109. return 1;
  110. }
  111. bool oszlop(int s,int o,int n)
  112. {
  113. for(int g=0;g<9;g++)
  114. {
  115. if(a[g][o]==n)
  116. return 0;
  117. }
  118. return 1;
  119. }
  120. bool negyzet(int s,int o,int n)
  121. {
  122. int sor=ceil((s+1)/3.);
  123. int oszlop=ceil((o+1)/3.);
  124. for(int g=(sor-1)*3;g<((sor-1)*3+3);g++)
  125. for(int h=(oszlop-1)*3;h<((oszlop-1)*3+3);h++)
  126. {
  127. if(a[g][h]==n)
  128. return 0;
  129. }
  130. return 1;
  131. }
Add Comment
Please, Sign In to add comment