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