fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. #define N 9
  6.  
  7. bool isSafe(int grid[N][N], int row, int col, int num) {
  8. for (int i = 0; i < N; i++) {
  9. if (grid[row][i] == num || grid[i][col] == num)
  10. return false;
  11. }
  12.  
  13. int startRow = row - row % 3;
  14. int startCol = col - col % 3;
  15. for (int i = 0; i < 3; i++) {
  16. for (int j = 0; j < 3; j++) {
  17. if (grid[i + startRow][j + startCol] == num)
  18. return false;
  19. }
  20. }
  21.  
  22. return true;
  23. }
  24.  
  25. bool findEmptyLocation(int grid[N][N], int &row, int &col) {
  26. for (row = 0; row < N; row++) {
  27. for (col = 0; col < N; col++) {
  28. if (grid[row][col] == 0)
  29. return true;
  30. }
  31. }
  32. return false;
  33. }
  34.  
  35. bool solveSudoku(int grid[N][N]) {
  36. int row, col;
  37.  
  38. // If there is no empty cell, puzzle is solved
  39. if (!findEmptyLocation(grid, row, col))
  40. return true;
  41.  
  42. for (int num = 1; num <= 9; num++) {
  43. if (isSafe(grid, row, col, num)) {
  44. grid[row][col] = num;
  45.  
  46. if (solveSudoku(grid))
  47. return true;
  48.  
  49. grid[row][col] = 0;
  50. }
  51. }
  52.  
  53. return false;
  54. }
  55.  
  56. void printGrid(int grid[N][N]) {
  57. for (int row = 0; row < N; row++) {
  58. for (int col = 0; col < N; col++)
  59. cout << grid[row][col] << " ";
  60. cout << endl;
  61. }
  62. }
  63.  
  64. int main() {
  65. int grid[N][N];
  66.  
  67. cout << "Enter the initial Sudoku puzzle (use 0 for empty cells):\n";
  68. for (int row = 0; row < N; row++) {
  69. for (int col = 0; col < N; col++) {
  70. cin >> grid[row][col];
  71. }
  72. }
  73.  
  74. if (solveSudoku(grid))
  75. printGrid(grid);
  76. else
  77. cout << "No solution exists" << endl;
  78.  
  79. return 0;
  80. }
  81.  
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
Enter the initial Sudoku puzzle (use 0 for empty cells):
2 1 -1063506144 5257 3 4 -1063530496 5257 -1063555040 
5257 -1063510816 5257 -1063533192 5257 -1064796922 5257 -1063506144 5257 
-2102456240 32764 -1063506144 5257 6 1 6 16 1780753920 
-1598711643 2 1 -1063510600 5257 -1063510600 5257 -1063509952 5257 
-1063502188 5257 -1064134709 5257 -1063510808 5257 -1064362058 5257 -1063510232 
5257 -1063510808 5257 -1063512160 5257 -1064361056 5257 -1063510240 5257 
-1063510528 5257 -1063510240 5257 -1064720904 5257 72703 1 -1065606904 
5257 -1064720752 5257 -1067321439 5257 1886130184 21845 1886130777 21845 
1 3 2 4 -2102455720 32764 1886119397 21845 -1063367904