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

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.

[Leetcode] Sudoku Solver

A sudoku puzzle...

 

[Leetcode] Sudoku Solver

...and its solution numbers marked in red.

 

暴力DFS!

 1 class Solution {
 2 public:
 3     bool isValid(vector<vector<char> > &board, int a, int b) {
 4         for (int i = 0; i < 9; ++i) {
 5             if (i != a && board[i][b] == board[a][b])
 6                 return false;
 7         }
 8         for (int j = 0; j < 9; ++j) {
 9             if (j != b && board[a][j] == board[a][b])
10                 return false;
11         }
12         int x = a / 3 * 3, y = b / 3 * 3;
13         for (int i = 0; i < 3; ++i) {
14             for (int j = 0; j < 3; ++j) {
15                 if (x + i != a && y + j != b && board[x + i][y + j] == board[a][b])
16                     return false;
17             }
18         }
19         return true;
20     }
21     
22     bool solveHelper(vector<vector<char> > &board) {
23         for (int i = 0; i < 9; ++i) {
24             for (int j = 0; j < 9; ++j) {
25                 if (board[i][j] == '.') {
26                     for (int k = 1; k <= 9; ++k) {
27                         board[i][j] = '0' + k;
28                         if (isValid(board, i, j) && solveHelper(board)) {
29                             return true;
30                         }
31                         board[i][j] = '.';
32                     }
33                     return false;
34                 }
35             }
36         }
37         return true;
38     }
39     
40     void solveSudoku(vector<vector<char> > &board) {
41         solveHelper(board);
42     }
43 };

 

相关文章:

  • 2022-12-23
  • 2021-08-30
  • 2021-07-11
  • 2021-11-21
  • 2022-03-07
  • 2022-01-05
  • 2022-01-18
猜你喜欢
  • 2021-06-11
  • 2021-10-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案