Determine if a Sudoku is valid, according to: Sudoku Puzzles – The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
思路
行搜索、列搜索、sub-box搜索,根据规则来就行了
代码
class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { set<char> workingSet; // Row char c; for(int row = 0; row<9; row++){ workingSet.clear(); for(int col=0; col<9; col++){ c = board[row][col]; if(c == '.') continue; if(workingSet.count(c) > 0) return false; workingSet.insert(c); } } // Col for(int col = 0; col<9; col++){ workingSet.clear(); for(int row=0; row<9; row++){ c = board[row][col]; if(c == '.') continue; if(workingSet.count(c) > 0) return false; workingSet.insert(c); } } // Sub-box for(int lPos=0; lPos < 9; lPos+=3){ for(int tPos=0; tPos<9; tPos+=3){ workingSet.clear(); for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ c = board[lPos+i][tPos+j]; if(c == '.') continue; if(workingSet.count(c) > 0) return false; workingSet.insert(c); } } } } return true; } };