answersLogoWhite

0

The code is below and i should also explain the algorithm. Well, What we are doing here is that we already defined the size to be 9x9 sudoku and are getting values using loops. All the empty spots are given UNASSIGNED value. Then we have functions to tell that if it is safe to put a value in the empty box by calculation and according to the rules of Sudoku it checks for is there any other some number horizontally and vertically and do the sum of the row and column is less than or equal to required or not. If the functions returns true then the program puts the value there.

  1. #include
  2. #define UNASSIGNED 0
  3. #define N 9
  4. bool FindUnassignedLocation(int grid[N][N], int &row, int &col);
  5. bool isSafe(int grid[N][N], int row, int col, int num);

  6. bool SolveSudoku(int grid[N][N])
  7. {
  8. int row, col;

  9. if (!FindUnassignedLocation(grid, row, col))
  10. return true; // success!

  11. for (int num = 1; num <= 9; num++)
  12. {

  13. if (isSafe(grid, row, col, num))
  14. {

  15. grid[row][col] = num;

  16. if (SolveSudoku(grid))
  17. return true;

  18. grid[row][col] = UNASSIGNED;
  19. }
  20. }
  21. return false;}

  22. bool FindUnassignedLocation(int grid[N][N], int &row, int &col)
  23. {
  24. for (row = 0; row < N; row++)
  25. for (col = 0; col < N; col++)
  26. if (grid[row][col] true)
  27. printGrid(grid);
  28. else
  29. printf("No solution exists");
  30. return 0;
  31. }






User Avatar

Wiki User

9y ago

What else can I help you with?