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.
解法一:
数独的规则就是行、列、9个3*3的cell中不能出现重复的数字。思路是创建三个矩阵,row, col, cell, row[i][c]表示第i行中出现了数字c, col[j][c] 表示第j列出现了数字c, cell[k][c]表示第k个cell出现了数字c。每次去检查 row, col, cell中对应元素是不是有一个为true。
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
// check size
if (board.size()!=9) return false;
//////
vector<vector<bool> > row_flag(9,vector<bool>(9,false));
vector<vector<bool> > col_flag(9,vector<bool>(9,false));
vector<vector<bool> > cell_flag(9,vector<bool>(9,false));
for(int i=0; i<9; i++){
if (board[i].size()!=9)
return false;
for (int j=0; j<9; j++){
if (!validFill(board[i][j]))
return false;
if (board[i][j] >= '1' && board[i][j] <= '9'){
int val = board[i][j] - '1';
if (row_flag[i][val] || col_flag[j][val] || cell_flag[3*(i/3)+j/3][val]) return false;
row_flag[i][val] = true;
col_flag[j][val] = true;
cell_flag[3*(i/3)+j/3][val] = true;
}
}
}
return true;
}
bool validFill(char c){
return c == '1' || c == '2' || c == '3' || c == '4' || c == '5' ||
c == '6' || c == '7' || c == '8' || c == '9' || c == '.';
}
};