当前位置: 首页 > 工具软件 > AI_Sudoku > 使用案例 >

[LeetCode] Sudoku Solver

慕容弘懿
2023-12-01

Just don't be scared by this problem :-) It's also very standard backtracking problem. This post shares a very concise code, which is rewritten below in C++.

 1 class Solution {
 2 public:
 3     void solveSudoku(vector<vector<char>>& board) {
 4         solve(board);
 5     }
 6 private:
 7     bool solve(vector<vector<char>>& board) {
 8         for (int r = 0; r < 9; r++) {
 9             for (int c = 0; c < 9; c++) {
10                 if (board[r][c] == '.') {
11                     for (char d = '1'; d <= '9'; d++) {
12                         if (isValid(board, r, c, d)) {
13                             board[r][c] = d;
14                             if (solve(board)) return true;
15                             board[r][c] = '.';
16                         }
17                     }
18                     return false;
19                 }
20             } 
21         }
22         return true;
23     }
24     bool isValid(vector<vector<char>>& board, int r, int c, char d) {
25         for (int row = 0; row < 9; row++)
26             if (board[row][c] == d) return false;
27         for (int col = 0; col < 9; col++)
28             if (board[r][col] == d) return false;
29         for (int row = (r / 3) * 3; row < (r / 3 + 1) * 3; row++)
30             for (int col = (c / 3) * 3; col < (c / 3 + 1) * 3; col++)
31                 if (board[row][col] == d) return false;
32         return true;
33     }
34 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4792415.html

 类似资料: