您的位置:首页 > 其它

[Leetcode 103] 37 Sudoku Solver

2013-08-09 10:45 323 查看
Problem:

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.

class Solution {
public:
void solveSudoku(vector<vector<char> > &board) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
solve(board);
}

private:
bool solve(vector<vector<char> > &board) {
int r, c;

if (noRemainingPos(board, r, c))
return true;

for (int i=1; i<=9; i++) {
if (noConflict(board, r, c, i+'0')) {
board[r][c] = i+'0';
if (solve(board)) return true;
board[r][c] = '.';
}
}

return false;
}

bool noRemainingPos(const vector<vector<char> > &b, int &r, int &c) {
for (int i=0; i<9; i++)
for (int j=0; j<9; j++) {
if (b[i][j] == '.') {
r = i;
c = j;
return false;
}

}

return true;
}

bool noConflict(const vector<vector<char> > &b, int r, int c, char n) {
return noConf(b, r, 0, 1, 9, n) && noConf(b, 0, c, 9, 1, n) && noConf(b, r/3*3, c/3*3, 3, 3, n);
}

bool noConf(const vector<vector<char> > &b, int r, int c, int rc, int cc, char n) {
for (int i=r; i<r+rc; i++)
for (int j=c; j<c+cc; j++) {
if (b[i][j] == n)
return false;
}

return true;
}

};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: