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

[LeetCode] Sudoku Solver

时间:2014-11-04 10:35:34      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   for   sp   div   

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,布布扣

...and its solution numbers marked in red.

 

终于到了朝思暮想的sudoku solver了, 有了Valid Sudoku的基础,我知道了用哈希表可以很方便的判断冲突。思路还是遍历这个board,这次是找到为空的位置,然后对可能的结果集进行筛选:把行、列、3x3出现的数字都去掉,剩下的就是可能的结果集。然后把结果集里的元素一个一个拿出来进行深度搜索,直到满足递归出口:row == 8 && col == 8 说明board遍历完毕,得到结果; 如果函数最终返回却没有满足那个条件的话,就说明此局无解。

在解此题时主要遇到的问题是对递归出口判断的模棱两可,还有传board的时候我老是喜欢传个引用,导致一次深搜改变了board。。这是个bug,在word breakII时也遇到过。总值对此题的理解还需深入,继续推敲。

 1 void solver(vector<vector<char>> board, int row, int col, vector<vector<char>> &ret) {
 2     if (board[row][col] != .) {
 3         if (row == 8 && col == 8) {
 4             ret = board;
 5             return;
 6         }
 7         else if (++col >= 9) {
 8             ++row;
 9             col = 0;
10         }
11         solver(board, row, col, ret);
12         return;
13     }
14     
15     // calculate solve space
16     unordered_set<char> set = preset;
17     // filter colum
18     for (int k = 0; k < 9; k++) {
19         char searched = board[k][col];
20         if (searched != . && set.find(searched) != set.end()) {
21             set.erase(searched);
22         }
23     }
24     // filter row
25     for (int k = 0; k < 9; k++) {
26         char searched = board[row][k];
27         if (searched != . && set.find(searched) != set.end()) {
28             set.erase(searched);
29         }
30     }
31     // filter 3*3
32     int square_row_offset = row / 3;
33     int square_col_offset = col / 3;
34     for (int k = square_row_offset * 3; k < square_row_offset * 3 + 3; k++) {
35         for (int l = square_col_offset * 3; l < square_col_offset * 3 + 3; l++) {
36             char searched = board[k][l];
37             if (searched != . && set.find(searched) != set.end()) {
38                 set.erase(searched);
39             }
40         }
41     }
42     
43     for (char ele: set) {
44         board[row][col] = ele;
45         
46         if (row == 8 && col == 8) {
47             ret = board;
48             return;
49         }
50         
51         solver(board, row, col+1, ret);
52     }
53 }
54 
55 
56 vector<vector<char>> sudokuSolver(vector<vector<char>> &board) {
57     vector<vector<char>> ret;
58     solver(board, 0, 0, ret);
59     return ret;
60 }

 

[LeetCode] Sudoku Solver

标签:style   blog   http   io   color   ar   for   sp   div   

原文地址:http://www.cnblogs.com/agentgamer/p/4072751.html

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