码迷,mamicode.com
首页 > 其他好文 > 详细

Sudoku Solver

时间:2014-07-16 21:52:48      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   for   

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.

bubuko.com,布布扣

A sudoku puzzle...

 

bubuko.com,布布扣

 

很好的例子理解递归,回朔,以及循环中的递归。

 

 1 class Solution {
 2 public:
 3     void solveSudoku(vector<vector<char> > &board) {
 4         process(board, 0,0);
 5         
 6     }
 7     bool process(vector<vector<char>> &board,int i,int j)
 8     {
 9 
10         if(j==9)
11         {
12             return process(board,i+1,0);//!!!
13         }
14         if(i==9)
15         {
16             //cout<<"true";
17             return true;
18         }
19         if(board[i][j]==.)
20         {
21             for(int k=1;k<10;k++)
22             {
23 
24                 if(isValid(board,i,j,k))
25                 {
26                 board[i][j]=0+k;
27                 if(process(board,i,j+1)) {return true;}
28                 board[i][j]=.;
29                 }
30                 
31             }
32 
33             return false;
34         }
35         else return process(board,i,j+1);
36         
37     }
38     bool isValid(vector<vector<char>> &board,int i, int j, int k)
39     {
40         
41         char qq=0+k;
42         for(int m=0;m<9;m++)
43         {
44             if(board[i][m]==qq){return false;}
45         }
46         for(int m=0;m<9;m++)
47         {
48             if(board[m][j]==qq)return false;
49         }
50         int m=i/3, n=j/3;
51         for(int p=m*3;p<m*3+3;p++)
52         {
53             for(int q=n*3;q<n*3+3;q++)
54             {
55                 if(board[p][q]==qq)return false;
56             }
57         }
58         return true;
59     }
60 };

 

Sudoku Solver,布布扣,bubuko.com

Sudoku Solver

标签:style   blog   http   color   io   for   

原文地址:http://www.cnblogs.com/hicandyman/p/3835683.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!