您的位置:首页 > 其它

Leetcode: Sudoku Solver

2014-02-23 00:14 218 查看
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.

基本思想比较简单就是brute force + backtrack,不过解的那个郁闷啊,很长时间。Debug了好久,才发现计算可用字母的时候没有加上起点坐标。写程序不能大意啊,必须谨慎,考虑周全。

class Solution {
public:
void solveSudoku(vector<vector<char> > &board) {
fillBoard(board, 0, 0);
}

bool fillBoard(vector<vector<char> > &board, int row, int col) {
if (row == board.size() - 1 && col == board.size()) {
return true;
}
else if (col == board.size()) {
col = 0;
++row;
}

if (board[row][col] != '.') {
return fillBoard(board, row, col + 1);
}
else {
vector<char> nearhits = findAvailable(board, row, col);
for (int i = 0; i < nearhits.size(); ++i) {
board[row][col] = nearhits[i];
if (fillBoard(board, row, col + 1)) {
return true;
}
board[row][col] = '.';
}
return false;
}

}

vector<char> findAvailable(vector<vector<char> > &board, int row, int col) {
static pair<int, int> points[] = {{0, 0,}, {0, 3}, {0, 6}, {3, 0}, {3, 3}, {3, 6}, {6, 0}, {6, 3}, {6, 6}};
set<char> nums;
pair<int, int> point = points[row / 3 * 3 + col / 3];

for (int i = 0; i < board.size(); ++i) {
if (board[row][i] != '.') {
nums.insert(board[row][i]);
}
if (board[i][col] != '.') {
nums.insert(board[i][col]);
}
int px = point.first + i / 3;
int py = point.second + i % 3;
if (board[px][py] != '.') {
nums.insert(board[px][py]);
}
}

vector<char> result;
for (char i = '1'; i <= board.size() + '0'; ++i) {
if (nums.find(i) == nums.end()) {
result.push_back(i);
}
}

return result;
}
};算是有些优化吧,计算可用的数字,然后依次填充,这样就不用判断数独是否合法了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode