-----QUESTION-----
Determine if a Sudoku is valid, according to:
The Sudoku board could be partially filled, where empty cells are filled with the character'.'
.
A partially filled sudoku which is valid.
-----SOLUTION-----
class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board) {
vector<bool> flag(board.size()+1, false);
//check line
for(int i = 0; i<9; i++)
{
for(int j = 0; j<9; j++)
{
if(board[i][j]=='.') continue;
if(flag[board[i][j]-'0']) return false;
flag[board[i][j]-'0'] = true;
}
flag.assign(board.size()+1,false);
}
flag.assign(board.size()+1,false);
//check column
for(int j = 0; j<9; j++)
{
for(int i = 0; i<9; i++)
{
if(board[i][j]=='.') continue;
if(flag[board[i][j]-'0']) return false;
flag[board[i][j]-'0'] = true;
}
flag.assign(board.size()+1,false);
}
flag.assign(board.size()+1,false);
//check small square
for(int i = 0; i < 9; i+=3){
for(int j = 0; j <9; j+=3){
for(int m = 0; m < 3; m++){
for(int n = 0; n < 3; n++){
if(board[i+m][j+n]=='.') continue;
if(flag[board[i+m][j+n]-'0']) return false;
flag[board[i+m][j+n]-'0'] = true;
}
}
flag.assign(board.size()+1,false);
}
}
return true;
}
};
如果没有'.',那么我们可以用以下的方法判断是否valid
bool check(vector<int> v) {
sort(v.begin(), v.end());
for (int i = 0; i < (int)v.size(); ++i) {
if (v[i] != i + 1) {
return false;
}
}
return true;
}
参数是某一行,某一列,或是某一个small square的9个元素