37. Sudoku Solver

小鱼儿 2023-07-06 09:59 77阅读 0赞

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

  1. Each of the digits 1-9 must occur exactly once in each row.
  2. Each of the digits 1-9 must occur exactly once in each column.
  3. Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

Empty cells are indicated by the character '.'.

format_png
A sudoku puzzle…

format_png 1
…and its solution numbers marked in red.

Note:

  • The given board contain only digits 1-9 and the character '.'.
  • You may assume that the given Sudoku puzzle will have a single unique solution.
  • The given board size is always 9x9.

题意:数独

  1. class Solution {
  2. public:
  3. bool isValidSudoku(vector<vector<char>>& board, int i,int j,int c)
  4. {
  5. for (int k = 0; k < 9; k++)
  6. {
  7. if (board[i][k] == c)
  8. return false;
  9. if (board[k][j] == c)
  10. return false;
  11. }
  12. int begin = (i / 3);
  13. int end = (j / 3);
  14. for (int k = begin * 3; k < (begin+1) * 3; k++)
  15. {
  16. for (int s = end * 3; s < (end + 1) * 3; s++)
  17. {
  18. if (board[k][s] == c)
  19. return false;
  20. }
  21. }
  22. return true;
  23. }
  24. bool Helper(vector<vector<char>>& board)
  25. {
  26. for (int i = 0; i < 9; i++)
  27. {
  28. for (int j = 0; j < 9; j++)
  29. {
  30. if (board[i][j] == '.')
  31. {
  32. for (char c = '1'; c <= '9'; c++)
  33. {
  34. if (isValidSudoku(board, i, j, c))
  35. {
  36. board[i][j] = c;
  37. if (Helper(board))
  38. {
  39. return true;
  40. }
  41. else
  42. {
  43. board[i][j] = '.';
  44. }
  45. }
  46. }
  47. return false;
  48. }
  49. }
  50. }
  51. return true;
  52. }
  53. void solveSudoku(vector<vector<char>>& board)
  54. {
  55. Helper(board);
  56. }
  57. };

发表评论

表情:
评论列表 (有 0 条评论,77人围观)

还没有评论,来说两句吧...

相关阅读