[LeetCode]Sudoku Solver

Sudoku Solver

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.

Valid Sudoku还是有区别的。这里默认有唯一解了,不需要全盘验证。

用到回溯的思想。在‘.’位置插入1-9数字,判断是否满足数独的条件,如果不满足,则回溯,直到‘.’添加的数字都满足。

 1 class Solution {
 2 public:
 3     bool isValidSudoku(vector<vector<char>>& board,int x,int y)
 4     {
 5         for(int i=0;i<9;i++)
 6         {
 7             if((i!=x)&&(board[x][y]==board[i][y]))
 8             {
 9                 return false;
10             }
11         }
12         for(int i=0;i<9;i++)
13         {
14             if((i!=y)&&(board[x][y]==board[x][i]))
15             {
16                 return false;
17             }
18         }
19         for(int m=x/3*3;m<x/3*3+3;m++)
20         {
21             for(int n=y/3*3;n<y/3*3+3;n++)
22             {
23                 if((m!=x)&&(n!=y)&&(board[m][n]==board[x][y]))
24                 {
25                     return false;
26                 }
27             }
28         }
29         return true;
30     }
31     
32     bool isSolveSudoku(vector<vector<char>>& board) {
33         for(int i=0;i<9;i++)
34         {
35             for(int j=0;j<9;j++)
36             {
37                 if(board[i][j]=='.')
38                 {
39                     for(int k=0;k<9;k++)
40                     {
41                         board[i][j]='1'+k;
42                         if((isValidSudoku(board,i,j))&&(isSolveSudoku(board)))
43                         {
44                             return true;
45                         }
46                         board[i][j]='.';
47                     }
48                     return false;
49                 }
50             }
51         }
52         return true;
53     }
54     
55     void solveSudoku(vector<vector<char>>& board) {
56         isSolveSudoku(board);
57     }
58 };
原文地址:https://www.cnblogs.com/Sean-le/p/4743247.html