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.
solution:空间换时间,设置多个二维数组分别记录横,纵,块中九个数字的出现次数,若重复出现则报错,反之该数独是valid的。
PS: 还需要判断数是否在1-9之间,若超出该范围也是错误的。
class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int si = board[0].size();
if(si <= 0)
return false;
vector< vector<bool> >rows(si,vector<bool>(si,false));
vector< vector<bool> >cols(si,vector<bool>(si,false));
vector< vector<bool> >blocks(si,vector<bool>(si,false));
for(int row = 0; row < si; row++)
{
for(int col = 0; col < si; col++)
{
char temp = board[ row ][ col ];
if(temp == '.')
continue;
int num = temp - '1';
if( rows[ row ][ num ] || cols[ col ][ num ] || blocks[ col/3 + row - row % 3 ][ num ] )
return false;
rows[ row ][ num ] = true;
cols[ col ][ num ] = true;
blocks[ col/3 + row - row % 3 ][ num ] = true;
}
}
return true;
}
};