Valid Sudoku
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.
不需要数独可解,只需要已经写入的数符合要求就可以
class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { set<char> row, col, box; for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { if(board[i][j] != '.') { if(row.find(board[i][j]) != row.cend()) return false; else row.insert(board[i][j]); } if(board[j][i] != '.') { if(col.find(board[j][i]) != col.cend()) return false; else col.insert(board[j][i]); } if(board[(i / 3) *3 + j / 3][(i % 3) * 3 + j % 3] != '.') { if(box.find(board[(i / 3) *3 + j / 3][(i % 3) * 3 + j % 3]) != box.cend()) return false; else box.insert(board[(i / 3) *3 + j / 3][(i % 3) * 3 + j % 3]); } } row.clear(); col.clear(); box.clear(); } return true; } };
- 每一行,每一列,每一个九格,保存一个set,如果发现有重复就返回
- 主要是从i,j推出九格的位置
- i/3为第几行 i%3为第几列
- 每一次判断完都需要把set清空,重新开始