Skip to content

Instantly share code, notes, and snippets.

@sitano
Created October 27, 2015 18:46
Show Gist options
  • Save sitano/b5245e9b925b77cdc7cc to your computer and use it in GitHub Desktop.
Save sitano/b5245e9b925b77cdc7cc to your computer and use it in GitHub Desktop.
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
for (int row = 0; row < 9; row ++) {
auto rowi = &board[row];
for (int col = 0; col < 9; col ++) {
if ((*rowi)[col] == '.') {
for (char a = '1'; a <= '9'; ++ a) {
if (can(board, col, row, a)) {
(*rowi)[col] = a;
solveSudoku(board);
if (isSolution(board)) {
return;
}
}
}
(*rowi)[col] = '.';
return;
}
}
}
}
bool can(vector<vector<char>>& board, int col, int row, char val) {
auto v = &board[row];
for (auto i = v->begin(); i != v->end(); ++ i) {
if (*i == val) {
return false;
}
}
for (int i = 0; i < 9; i ++) {
if (board[i][col] == val) {
return false;
}
}
const int sj = row / 3;
const int si = col / 3;
for (int j = sj * 3; j < sj * 3 + 3; j ++) {
for (int i = si * 3; i < si * 3 + 3; i ++) {
if (board[j][i] == val) {
return false;
}
}
}
return true;
}
bool isSolution(vector<vector<char>>& board) {
for (auto row = board.begin(); row != board.end(); ++ row) {
for (auto col = row->begin(); col != row->end(); ++ col) {
if (*col == '.') {
return false;
}
}
}
return true;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment