fork(2) download
  1. #include <iostream>
  2. using namespace std;
  3. #define SQUARE_SIZE 9
  4.  
  5. int anyLine = 0;
  6. int currLine = 0;
  7. int numSolutions = 0;
  8.  
  9.  
  10. // swap two values in the square.
  11. void swap (int arr[], int idxa, int idxb)
  12. {
  13. int tmp = arr[idxa];
  14. arr[idxa] = arr[idxb];
  15. arr[idxb] = tmp;
  16. }
  17.  
  18. void printArray(int arr[])
  19. {
  20. for (int i = 0; i < SQUARE_SIZE; i++)
  21. {
  22. cout << arr[i] << " ";
  23. if((i+1) % 3 == 0)
  24. cout << endl;
  25. }
  26. cout << endl;
  27. }
  28.  
  29. // this function tests to see if we have a "good" arrangment of numbers
  30. // i.e the sum of each row, colum and diagonal is equal
  31.  
  32. bool checkArr(int arr[])
  33. {
  34. anyLine = arr[0] + arr[1] + arr[2];
  35. currLine = 0;
  36. for (int i = 0; i < SQUARE_SIZE; i++)
  37. {
  38. currLine += arr[i];
  39. if((i+1) % 3 == 0)
  40. {
  41. if (currLine != anyLine)
  42. return false;
  43. currLine = 0;
  44. }
  45. }
  46. // check vertically
  47. for (int col = 0; col <3; col++)
  48. {
  49. for (int row = 0; row <3; row++)
  50. {
  51. currLine += arr[col + 3 * row];
  52. }
  53. if (currLine != anyLine)
  54. return false;
  55. currLine = 0;
  56. }
  57.  
  58. // check the diagonals
  59. if ((arr[2] + arr[4] + arr[6]) != anyLine)
  60. return false;
  61.  
  62. if ((arr[0] + arr[4] + arr[8]) != anyLine)
  63. return false;
  64.  
  65. return true;
  66. }
  67.  
  68. void solve(int arr[], int pos)
  69. {
  70.  
  71. if (pos == 8)
  72. {
  73.  
  74. if (checkArr(arr))
  75. {
  76. printArray(arr);
  77. numSolutions++;
  78. }
  79.  
  80. }else
  81. {
  82. for (int i = pos ; i < 9; i++)
  83. {
  84.  
  85. /*if (checkArr(arr))
  86.   {
  87.   printArray(arr);
  88.   numSolutions++;
  89.   }*/
  90.  
  91. //if (i == pos) continue;
  92.  
  93. swap(arr,pos,i);
  94. solve(arr,pos +1);
  95. swap(arr,pos,i);
  96.  
  97. }
  98. }
  99. }
  100.  
  101. int main()
  102. {
  103.  
  104. int arr[SQUARE_SIZE]= { 1,2,3,4,5,6,7,8,9 };
  105.  
  106. solve(arr,0);
  107. cout << "number of solutions is: " << numSolutions<< endl;
  108.  
  109. return 0;
  110. }
  111.  
Success #stdin #stdout 0.01s 3140KB
stdin
Standard input is empty
stdout
2 7 6 
9 5 1 
4 3 8 

2 9 4 
7 5 3 
6 1 8 

4 3 8 
9 5 1 
2 7 6 

4 9 2 
3 5 7 
8 1 6 

6 1 8 
7 5 3 
2 9 4 

6 7 2 
1 5 9 
8 3 4 

8 3 4 
1 5 9 
6 7 2 

8 1 6 
3 5 7 
4 9 2 

number of solutions is: 8