- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 53 lines of C++ from the credited upstream file solveSudoku.cpp.
- The implementation visibly relies on sequence storage.
- 7 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4 5class Solution {6 public:7 void solveSudoku(vector<vector<char> > &board) {8 solver(board);9 }10 private:11 bool solver(vector<vector<char> > &board) {12 for(int i = 0; i < 9; ++i) {13 for(int j = 0; j < 9; ++j) {14 if(board[i][j] == '.') {15 for(int k = 0; k < 9; ++k) {16 board[i][j] = '1' + k;17 if(isValid(board, i, j) && solver(board)) {18 return true;19 }20 board[i][j] = '.';21 }22 return false;23 }24 }25 }26 return true;27 }28 29 bool isValid(vector<vector<char> > &board, int x, int y) {30 31 for(int i = 0; i < 9; ++i) {32 if(i != x && board[i][y] == board[x][y])33 return false;34 }35 36 37 for(int j = 0; j < 9; ++j) {38 if(j != y && board[x][j] == board[x][y])39 return false;40 }41 42 43 for(int i = 3 * (x / 3); i < 3 * (x / 3 + 1); ++i) {44 for(int j = 3 * (y / 3); j < 3 * (y / 3 + 1); ++j) {45 if(!(i == x && j == y) && board[i][j] == board[x][y])46 return false;47 }48 }49 50 return true;51 }52};53