[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++.

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

 

posted @ 2015-09-08 17:35  jianchao-li  阅读(219)  评论(0编辑  收藏  举报