• Source
    1. #include<bits/stdc++.h>
    2.  
    3. using namespace std;
    4.  
    5. int grid[10][10],N,n;
    6.  
    7. bool UsedInRow(int row,int num)
    8. {
    9. for(int col=0; col<N; col++)
    10. {
    11. if(grid[row][col]==num)
    12. {
    13. return true;
    14. }
    15. }
    16.  
    17. return false;
    18. }
    19.  
    20. bool UsedInCol(int col,int num)
    21. {
    22. for(int row=0; row<N; row++)
    23. {
    24. if(grid[row][col]==num)
    25. {
    26. return true;
    27. }
    28. }
    29.  
    30. return false;
    31. }
    32.  
    33. bool UsedInBox(int BoxStRow,int BoxStCol,int num)
    34. {
    35. for(int row=0; row<n; row++)
    36. {
    37. for(int col=0; col<n; col++)
    38. {
    39. if(grid[row+BoxStRow][col+BoxStCol]==num)
    40. {
    41. return true;
    42. }
    43. }
    44. }
    45.  
    46. return false;
    47. }
    48.  
    49. bool isSafe(int row,int col,int num)
    50. {
    51. return !UsedInRow(row,num)&&
    52. !UsedInCol(col,num)&&
    53. !UsedInBox(row-row%n,col-col%n,num);
    54. }
    55.  
    56. bool SuDoku()
    57. {
    58. bool tag = false;
    59.  
    60. int row,col;
    61.  
    62. for(row=0; row<N; row++)
    63. {
    64. for(col=0; col<N; col++)
    65. {
    66. if(grid[row][col]==0)
    67. {
    68. tag = true;
    69.  
    70. break;
    71. }
    72. }
    73.  
    74. if(tag)
    75. {
    76. break;
    77. }
    78. }
    79.  
    80. if(!tag)
    81. {
    82. return true;
    83. }
    84.  
    85. for(int num=1; num<=N; num++)
    86. {
    87. if(isSafe(row,col,num))
    88. {
    89. grid[row][col] = num;
    90.  
    91. if(SuDoku())
    92. {
    93. return true;
    94. }
    95.  
    96. grid[row][col] = 0;
    97. }
    98. }
    99.  
    100. return false;
    101. }
    102.  
    103. int main()
    104. {
    105. int tc = 1;
    106.  
    107. while(scanf("%d",&n)==1)
    108. {
    109. N = n*n;
    110.  
    111. for(int i=0; i<N; i++)
    112. {
    113. for(int j=0; j<N; j++)
    114. {
    115. scanf("%d",&grid[i][j]);
    116. }
    117. }
    118.  
    119. if(tc!=1)
    120. {
    121. puts("");
    122. }
    123.  
    124. tc = 2;
    125.  
    126. if(SuDoku())
    127. {
    128. for(int i=0; i<N; i++)
    129. {
    130. printf("%d",grid[i][0]);
    131.  
    132. for(int j=1; j<N; j++)
    133. {
    134. printf(" %d",grid[i][j]);
    135. }
    136.  
    137. puts("");
    138. }
    139. }
    140. else
    141. {
    142. puts("NO SOLUTION");
    143. }
    144. }
    145.  
    146. return 0;
    147. }