您的位置:首页 > 其它

leetcode 037 —— Sudoku Solver

2015-07-15 21:42 351 查看
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.

思路:这道题很有难度。有了前面的判断,应该解出来还算顺利

class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
scan(0, board);
}
bool scan(int level, vector<vector<char>>& board){
if (level == 81)
return true;
int i = level / 9; //计算行号
int j = level % 9; //计算列号

if (board[i][j] == '.'){
for (int k = 1; k <= 9; k++){
board[i][j] = k + '0';
if (isValid(i, j, k + '0', board)){
if (scan(level + 1, board)){
return true;
}
}
board[i][j] = '.';
}
}
else{
if (scan(level + 1, board))
return true;
}
return false; //一定不能忘记return false

}

bool isValid(int i, int j, char val, vector<vector<char>>& board){
//鉴别行的有效性
int l = j, r = j;
while (--l >= 0){
if (board[i][l] == val) return false;
}
while (++r < 9){
if (board[i][r] == val) return false;
}
//鉴别列
l = i; r = i;
while (--l >= 0){
if (board[l][j] == val) return false;
}
while (++r < 9){
if (board[r][j] == val) return false;
}
//鉴别单元格

int out = 3 * (i / 3) + j / 3; //第out个大单元格
int in = 3 * (i % 3) + j % 3; //第in个小单元格
l = r = in;
while (--l >= 0){
if (board[3 * (out / 3) + l / 3][(out % 3) * 3 + l % 3] == val) return false;
}
while (++r < 9){
if (board[3 * (out / 3) + r / 3][(out % 3) * 3 + r % 3] == val) return false;
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: