Sudoku Solver
2015-07-14 20:42
288 查看
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.
解:
bool isValid(vector<vector<char>> & board, int x, int y){
for(int i=0; i<board.size(); i++){
if(board[i][y]=='.' || i==x)
continue;
if(board[x][y]==board[i][y])
return false;
}
for(int i=0; i<board[0].size(); i++){
if(board[x][i]=='.' || i==y)
continue;
if(board[x][y]==board[x][i])
return false;
}
int startx=x/3*3;
int starty=y/3*3;
for(int i=startx; i<startx+3; i++){
for(int j=starty; j<starty+3; j++){
if(board[i][j]=='.' || i==x || j==y)
continue;
if(board[i][j]==board[x][y])
return false;
}
}
return true;
}
bool solveSudo(vector<vector<char>>& board) {
for(int i=0; i<board.size(); i++){
for(int j=0; j<board[0].size(); j++){
if(board[i][j]!='.')
continue;
int k;
for(k=1; k<10; k++){
board[i][j]=k+'0';
if(isValid(board, i, j))
{
if(solveSudo(board))
return true;
}
board[i][j]='.';
}
return false;//没有任何判断,直接返回false
}
}
return true;
}
void solveSudoku(vector<vector<char>>& board) {
solveSudo(board);
}
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.
解:
bool isValid(vector<vector<char>> & board, int x, int y){
for(int i=0; i<board.size(); i++){
if(board[i][y]=='.' || i==x)
continue;
if(board[x][y]==board[i][y])
return false;
}
for(int i=0; i<board[0].size(); i++){
if(board[x][i]=='.' || i==y)
continue;
if(board[x][y]==board[x][i])
return false;
}
int startx=x/3*3;
int starty=y/3*3;
for(int i=startx; i<startx+3; i++){
for(int j=starty; j<starty+3; j++){
if(board[i][j]=='.' || i==x || j==y)
continue;
if(board[i][j]==board[x][y])
return false;
}
}
return true;
}
bool solveSudo(vector<vector<char>>& board) {
for(int i=0; i<board.size(); i++){
for(int j=0; j<board[0].size(); j++){
if(board[i][j]!='.')
continue;
int k;
for(k=1; k<10; k++){
board[i][j]=k+'0';
if(isValid(board, i, j))
{
if(solveSudo(board))
return true;
}
board[i][j]='.';
}
return false;//没有任何判断,直接返回false
}
}
return true;
}
void solveSudoku(vector<vector<char>>& board) {
solveSudo(board);
}
相关文章推荐
- Permutations II,Sudoku Solver,Merge k Sorted Lists
- DFS解数独问题
- POJ 3074 suduku
- Valid Sudoku
- Sudoku Solver
- HDU Sudoku Killer
- Sudoku Solver解题报告
- LeetCode 35. Valid Sudoku
- sudoku--Knuth's Algorithm X
- POJ2676--Sudoku
- Sudoku Puzzles - 九宫格(数独)游戏
- Open Source Quantum Computing
- Sudoku
- Sudoku poj2676 (dfs)
- 利用Caffe训练模型(solver、deploy、train_val)+python使用已训练模型
- Leetecode 36 37 Sudoku问题
- Valid Sudoku
- caffe学习笔记1 SGD solver
- 【用Python学习Caffe】5. 生成solver文件
- caffe中解析solver.prototxt到类SolverParameter的过程解析