[Leetcode 103] 37 Sudoku Solver

Problem:

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.

A sudoku puzzle...

...and its solution numbers marked in red.

Analysis:

The basic dfs problem. Notice the structure for DFS function. It's a well structured program abstraction.

Also notice when judging whether there's conflict in a sub 3*3 grid, the start point is i/3 * 3 and j/3*3. Please don't forget to multiple the second 3. Or that's not right

Code:

 1 class Solution {
 2 public:
 3     void solveSudoku(vector<vector<char> > &board) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         solve(board);
 7     }
 8     
 9 private:
10     bool solve(vector<vector<char> > &board) {
11         int r, c;
12 
13         if (noRemainingPos(board, r, c))
14             return true;
15 
16         for (int i=1; i<=9; i++) {
17             if (noConflict(board, r, c, i+'0')) {
18                 board[r][c] = i+'0';   
19                 if (solve(board)) return true;
20                 board[r][c] = '.';
21             }
22         }
23         
24         return false;
25     }
26     
27     bool noRemainingPos(const vector<vector<char> > &b, int &r, int &c) {
28         for (int i=0; i<9; i++)
29             for (int j=0; j<9; j++) {
30                 if (b[i][j] == '.') {
31                     r = i;
32                     c = j;
33                     return false;
34                 }
35                 
36             }
37         
38         return true;
39     }
40     
41     bool noConflict(const vector<vector<char> > &b, int r, int c, char n) {
42         return noConf(b, r, 0, 1, 9, n) && noConf(b, 0, c, 9, 1, n) && noConf(b, r/3*3, c/3*3, 3, 3, n);    
43     }
44     
45     bool noConf(const vector<vector<char> > &b, int r, int c, int rc, int cc, char n) {
46         for (int i=r; i<r+rc; i++)
47             for (int j=c; j<c+cc; j++) {
48                 if (b[i][j] == n)
49                     return false;
50             }
51         
52         return true;
53     }
54     
55 };
View Code
原文地址:https://www.cnblogs.com/freeneng/p/3247565.html