Sudoku Solver
2015-09-04 01:44
405 查看
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.
![](http://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png)
A sudoku puzzle...
![](http://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Sudoku-by-L2G-20050714_solution.svg/250px-Sudoku-by-L2G-20050714_solution.svg.png)
...and its solution numbers marked in red.
Solution:
Empty cells are indicated by the character
'.'.
You may assume that there will be only one unique solution.
![](http://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png)
A sudoku puzzle...
![](http://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Sudoku-by-L2G-20050714_solution.svg/250px-Sudoku-by-L2G-20050714_solution.svg.png)
...and its solution numbers marked in red.
Solution:
class Solution { public: void solveSudoku(vector<vector<char>>& board) { memset(row, true, sizeof(row)); memset(col, true, sizeof(col)); memset(block, true, sizeof(block)); for(int i = 0; i < 9; ++i) for(int j = 0; j < 9; ++j) { if(board[i][j] != '.') { int k = board[i][j] - '0'; row[i][k] = false; col[j][k] = false; block[i/3*3+j/3][k] = false; } } dfs(board, 0); } bool dfs(vector<vector<char> >&board, int index) { if(index > 80) return true; int i = index / 9, j = index % 9; if(board[i][j] != '.') return dfs(board, index + 1); for(int k = 1; k <= 9; ++k) { if(row[i][k] && col[j][k] && block[i/3*3+j/3][k]) { board[i][j] = k + '0'; row[i][k] = false; col[j][k] = false; block[i/3*3+j/3][k] = false; if(dfs(board, index + 1)) return true; row[i][k] = true; col[j][k] = true; block[i/3*3+j/3][k] = true; } } board[i][j] = '.'; return false; } private: bool row[9][10]; bool col[9][10]; bool block[9][10]; };
相关文章推荐
- 第一次写博客...
- c friend -- 友元
- c++ virturn function -- 虚函数
- c friend -- 友元
- c++ virturn function -- 虚函数
- c++ anonymous union,struct -- 匿名联合体和机构体
- c++ anonymous union,struct -- 匿名联合体和机构体
- c++ anonymous namespace -- 匿名空间
- c++ inheritance -- 继承
- POJ 3630 解题报告
- c++ anonymous namespace -- 匿名空间
- c++ inheritance -- 继承
- grep,egrep 及正则表达式
- c++ 类名和enum时重复时要在类名前加class::
- c vs c++ in strcut and class
- C++ operator overload -- 操作符重载
- c++ 类名和enum时重复时要在类名前加class::
- c vs c++ in strcut and class
- C++ operator overload -- 操作符重载
- C++ delete 和 delete []