您的位置:首页 > 其它

Leetcode dfs Sudoku Solver

2014-09-07 13:05 363 查看


Sudoku Solver

 Total Accepted: 11799 Total
Submissions: 56732My Submissions

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.

题意:填充数独,返回是否填充成功

思路:dfs

找一个还没填充的位置,尝试填写0-9其中的一个数字,判断是否理。

如果合理,则可以转移到一个同样子问题,所以可以采用递归的方式实现。

bool solveSudoku(vector<vector<char> >&board)

返回是否成功填充当前状态为 board的数独

bool isValid(const vector<vector<char> >&board, int x, int y){
//检查行
for(int j = 0; j < 9; ++j) if(j != y && board[x][j] == board[x][y]) return false;
//检查列
for(int i = 0; i < 9; ++i) if(i != x && board[i][y] == board[x][y]) return false;
//检查小方块
for(int i = 0; i < 3; ++i)
for(int j = 0; j < 3; ++j){
if(!(x/3 * 3 + i == x && y /3 * 3 + j == y) && board[x/3 * 3 + i][y /3 * 3 + j] == board[x][y]) return false;
}
return true;
}

bool solveSudoku(vector<vector<char> >&board)
{
for(int i = 0; i < 9; ++i){
for(int j = 0; j < 9; ++j){
if(board[i][j] == '.'){
for(int k = 0; k < 9; ++k){
board[i][j] = k + '1' ;
if(isValid(board, i, j) && solveSudoku(board)) return true;
board[i][j] = '.';
}
return false;
}
}
}
return true; //漏写了这句,WA了好多次
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: