36. 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.
解析
- 只是检测每行,每列,每个小方格是否满足九宫格的定义;使用hash表节省空间
- 另外就是小方格的坐标转换
[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3]
需要技巧
// 36. Valid Sudoku 数独/九宫格问题
class Solution_36 {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int row = board.size();
int col = board[0].size();
unordered_map<char,int> row_mp; // <char, bool>
unordered_map<char,int> col_mp;
unordered_map<char, int> diagonal; //对角线; sub-boxes
for (int i = 0; i < row;i++)
{
for (int j = 0; j < col;j++)
{
if (board[i][j]!='.' && row_mp.find(board[i][j])!=row_mp.end())
{
return false; //已经存在
}
else
{
row_mp[board[i][j]]++;
}
if (board[j][i] != '.'&& col_mp.find(board[j][i]) != col_mp.end())
{
return false;
}
else
{
col_mp[board[j][i]]++;
}
if (board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3] != '.'&& diagonal.find(board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3]) != diagonal.end()) // //第i个九宫格第j个格子
{
return false;
}
else
{
diagonal[board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3]]++;
}
}
col_mp.clear();
row_mp.clear();
diagonal.clear();
}
return true;
}
};
题目来源