classSolution {public:boolisValidSudoku(vector<vector<char>>& board) { bitset<9> check; // Check each rowfor(int row=0; row<board.size(); row++) { // reset bitset to all 0check.reset();for(int col=0; col<9; col++) {if(board[row][col] =='.') continue;else{if(check.test(board[row][col] -'1')) {returnfalse; }else {check.set(board[row][col] -'1'); } } } } // Check each columnfor(int col=0; col<9; col++) { // reset bitset to all 0check.reset();for(int row=0; row<9; row++) {if(board[row][col] =='.') continue;else{if(check.test(board[row][col] -'1')) {returnfalse; }else {check.set(board[row][col] -'1'); } } } } // Check each 3x3 blockfor(int row=0; row<board.size(); row+=3) {for(int col=0; col<9; col+=3) { // reset bitset to all 0check.reset(); // iterate through 3x3 blockfor(int i=0; i<3; i++) {for(int j=0; j<3; j++) {if(board[row+i][col+j] =='.') continue;else{if(check.test(board[row+i][col+j] -'1')) {returnfalse; }else {check.set(board[row+i][col+j] -'1'); } } } } } }returntrue; }};// idea: go through each row/column/3x3 block and count the number, if one number appears more than 1 time, then return false
這樣解的效率有點差,因為會需要 go through 整個 matrix 三次,雖然跑起來的結果看起來還可以:
Runtime: 8 ms, faster than 99.49% of C++ online submissions for Valid Sudoku. Memory Usage: 9.5 MB, less than 72.81% of C++ online submissions for Valid Sudoku.