您的位置:首页 > 其它

[LeetCode] Sudoku Solver

2014-06-25 17:11 274 查看
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.

题目的输入保证是有效的。用回溯法我们只要检查新加入的值能否在行、列以及小方块里有效即可,没有必要检查整个矩阵。

其实就是对于每一个'.' 尝试1~9 9个值,如果合法,就继续查下一个'.' ,如果非法,尝试下一个值。

若对于某一个'.' 1~9都尝试过且都失败了,就是无解,可以提前返回。

此题是边检查边求解。。

class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board, int x, int y) {
int row, col;

// Same value in the same column?
for (row = 0; row < 9; ++row) {
if ((x != row) && (board[row][y] == board[x][y])) {
return false;
}
}

// Same value in the same row?
for (col = 0; col < 9; ++col) {
if ((y != col) && (board[x][col] == board[x][y])) {
return false;
}
}

// Same value in the 3 * 3 block it belong to?
for (row = (x / 3) * 3; row < (x / 3 + 1) * 3; ++row) {
for (col = (y / 3) * 3; col < (y / 3 + 1) * 3; ++col) {
if ((x != row) && (y != col) && (board[row][col] == board[x][y])) {
return false;
}
}
}

return true;
}

// 内部check,能否找到结果用bool返回值标示
bool internalSolveSudokuCheck(vector<vector<char> > &board) {
for (int row = 0; row < 9; ++row) {
for (int col = 0; col < 9; ++col) {
if ('.' == board[row][col]) {
// 对每一个'.' 尝试 1~9,如果不合法,立刻返回
for (int i = 1; i <= 9; ++i) {
board[row][col] = '0' + i;

if (isValidSudoku(board, row, col)) {
if (internalSolveSudokuCheck(board)) {
return true;
}
}
//如果不合法,回复'.',进入下次尝试
board[row][col] = '.';
}
//对于某一个'.',尝试1~9都不行,就返回false
return false;
}
}
}

return true;
}

void solveSudoku(vector<vector<char> > &board) {
internalSolveSudokuCheck(board);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: