[LeetCode] Sudoku Solver

简介: 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++.

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 };

 

目录
相关文章
|
算法
LeetCode - 37. Sudoku Solver
37. Sudoku Solver  Problem's Link  ---------------------------------------------------------------------------- Mean:  求解数独.
953 0
LeetCode - 36. Valid Sudoku
36. Valid Sudoku  Problem's Link  ---------------------------------------------------------------------------- Mean:  给定一个数独,判断这个数独是否合法.
915 0
|
人工智能 Java
LeetCode 36 Valid Sudoku(有效数独)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50118647 翻译 数独板被部分填充,空格部分用'.'来填充。
942 0
|
2月前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
3月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
56 6
|
3月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
113 2