Created
October 27, 2015 18:46
-
-
Save sitano/b5245e9b925b77cdc7cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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