Created
October 27, 2015 18:58
-
-
Save sitano/4f63b8496c2f0a3bce9f to your computer and use it in GitHub Desktop.
not best, but 8ms - beats 77.99% of cpp submissions.
This file contains hidden or 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 { | |
private: | |
int flags[3][3] = {{0}}; | |
int rows[9] = {0}; | |
int cols[9] = {0}; | |
int count = 0; | |
deque<pair<int, int>> s; | |
public: | |
void solveSudoku(vector<vector<char>>& board) { | |
for (int row = 0; row < 9; row ++) { | |
for (int col = 0; col < 9; col++) { | |
char sym = board[row][col]; | |
if (sym == '.') { | |
s.push_front(make_pair(row, col)); | |
} else { | |
int num = sym - '0'; | |
int rowi = row / 3; | |
int coli = col / 3; | |
int mask = 1 << num; | |
flags[rowi][coli] |= mask; | |
rows[row] |= mask; | |
cols[col] |= mask; | |
count ++; | |
} | |
} | |
} | |
if (count == 81) { | |
return; | |
} | |
dfs(board); | |
} | |
void dfs(vector<vector<char>>& board) { | |
if (!s.empty()) { | |
auto pair = s.back(); | |
s.pop_back(); | |
int row = pair.first; | |
int col = pair.second; | |
int rowi = row / 3; | |
int coli = col / 3; | |
int a = flags[rowi][coli]; | |
int b = rows[row]; | |
int c = cols[col]; | |
for (int i = 1; i < 10; i ++) { | |
int mask = 1 << i; | |
if (!((rows[row] | cols[col] | flags[rowi][coli]) & mask)) { | |
board[row][col] = '0' + (char)i; | |
count ++; | |
flags[rowi][coli] = a | mask; | |
rows[row] = b | mask; | |
cols[col] = c | mask; | |
dfs(board); | |
if (count == 81) { | |
return; | |
} | |
flags[rowi][coli] = a; | |
rows[row] = b; | |
cols[col] = c; | |
} | |
} | |
board[row][col] = '.'; | |
count --; | |
s.push_back(pair); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment