class Solution {
private:
bool search(vector<vector<char>>& board, int r, int c, bool rTakens[][9], bool cTakens[][9], bool subTakens[][9])
{
if(r == 9) return true; //level checking;
if(c == 9) return search(board, r+1, 0, rTakens, cTakens, subTakens);
if(board[r][c] != '.') return search(board, r, c+1, rTakens, cTakens, subTakens);
for(char a = '1'; a <= '9'; ++a) //try different cases;
{
int num = a -'0', k = r/3*3+c/3;
if(!(rTakens[r][num] || cTakens[c][num] || subTakens[k][num])) //filter out the invalid;
{
rTakens[r][num] = cTakens[c][num] = subTakens[k][num] = true;
board[r][c] = a;
if(search(board, r, c+1, rTakens, cTakens, subTakens)) return true;
board[r][c] = '.'; //restore to its original state;
rTakens[r][num] = cTakens[c][num] = subTakens[k][num] = false;
}
}
return false;
}
public:
//AC - 4ms - best submission;
void solveSudoku(vector<vector<char>>& board)
{
bool rTakens[9][9]{{false}}, cTakens[9][9]{{false}}, subTakens[9][9]{{false}};
for(int r = 0; r < 9; ++r) //initialize the takens;
for(int c = 0; c < 9; ++c)
if(board[r][c] != '.')
{
int num = board[r][c] -'0', k = r/3*3+c/3;
rTakens[r][num] = cTakens[c][num] = subTakens[k][num] = true;
}
search(board, 0, 0, rTakens, cTakens, subTakens); //time to search and fill up the board;
}
};
The solution above is quite direct and efficient to solve the unique Sudoku but there is a question about it that confuses me a lot:
board[r][c] = '.'; //restore to its original state;
Why must I add this? if the current fill-up is okay then it will just return, if it's not then the answer will be in the following candidates which will replace it before further searching; so only resetting the tokens is necessary here, as I understand. But when I remove it, the result will be wrong. And it's tricky to trace the whole process, so here I am searching for some helpful ideas.
Thanks for your time and answers for this in advance!
For a specific cell of the board, let's suppose the unique answer of the first '.' cell is '2' then when we first try '1' for the first cell, then all the following '.' cells will fail and if we do not restore them after searching, then when we try '2' for the first '.' cell, the original '.' cells will be already filled up with un-'.' which will end the searching directly and return a wrong result.