fork(1) download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int matrica[9][9];
  6.  
  7. bool moze_broj(int red, int kolona, int broj)
  8. {
  9. for (int x = 0; x < 9; x++)
  10. if (matrica[red][x] == broj or matrica[x][kolona] == broj)
  11. return false;
  12. int pocetak_i = red - red % 3;
  13. int pocetak_j = kolona - kolona % 3;
  14. for (int i = 0; i < 3; i++)
  15. for (int j = 0; j < 3; j++)
  16. if (matrica[pocetak_i + i][pocetak_j + j] == broj)
  17. return false;
  18. return true;
  19. }
  20.  
  21. bool sudoku()
  22. {
  23. for (int i = 0; i < 9; i++)
  24. for (int j = 0; j < 9; j++)
  25. if (matrica[i][j] == 0)
  26. {
  27. for (int broj = 1; broj < 10; broj ++)
  28. if (moze_broj(i, j, broj))
  29. {
  30. matrica[i][j] = broj;
  31. if (sudoku())
  32. return true;
  33. matrica[i][j] = 0;
  34. }
  35. return false;
  36. }
  37. return true;
  38. }
  39.  
  40. int main()
  41. {
  42. for (int i = 0; i < 9; i++)
  43. {
  44. string linija;
  45. cin >> linija;
  46. for (int j = 0; j < 9; j++)
  47. matrica[i][j] = linija[j] - '0';
  48. }
  49. if (sudoku())
  50. for (int i = 0; i < 9; i++)
  51. {
  52. for (int j = 0; j < 9; j++)
  53. cout << matrica[i][j] << " ";
  54. cout << endl;
  55. }
  56. return 0;
  57. }
Success #stdin #stdout 0s 5320KB
stdin
749030680
006508000
000760324
800057060
407000508
050980002
184076000
000403800
063010247
stdout
7 4 9 1 3 2 6 8 5 
3 2 6 5 4 8 1 7 9 
5 1 8 7 6 9 3 2 4 
8 9 2 3 5 7 4 6 1 
4 3 7 6 2 1 5 9 8 
6 5 1 9 8 4 7 3 2 
1 8 4 2 7 6 9 5 3 
2 7 5 4 9 3 8 1 6 
9 6 3 8 1 5 2 4 7