topic
Please click
train of thought
Use subscripts to store the number of occurrences of the corresponding element
First two layers of for loop to judge whether each line meets the requirements
Then two layers of for loop to judge whether each column meets the requirements
Write a function to judge whether every three rows and three columns meet the requirements, and pass in parameters to change the end position of revelation
the code
bool isBoard ( vector< vector< char >> & board, int b1, int b2, int e1, int e2) {
vector< int > numbers ( 10 ) ;
for ( int i= b1; i< e1; i++ ) {
for ( int j= b2; j< e2; j++ ) {
if ( board[ i] [ j] == '.' ) continue ;
int n= board[ i] [ j] - '0' ;
numbers[ n] ++ ;
if ( numbers[ n] > 1 ) return false ;
}
}
return true ;
}
bool isValidSudoku ( vector< vector< char >> & board) {
for ( int i= 0 ; i< 9 ; i++ ) {
vector< int > numbers ( 10 ) ;
for ( int j= 0 ; j< 9 ; j++ ) {
if ( board[ i] [ j] == '.' ) continue ;
int n= board[ i] [ j] - '0' ;
numbers[ n] ++ ;
if ( numbers[ n] > 1 ) return false ;
}
}
for ( int j= 0 ; j< 9 ; j++ ) {
vector< int > numbers ( 10 ) ;
for ( int i= 0 ; i< 9 ; i++ ) {
if ( board[ i] [ j] == '.' ) continue ;
int n= board[ i] [ j] - '0' ;
numbers[ n] ++ ;
if ( numbers[ n] > 1 ) return false ;
}
}
bool ret1= isBoard ( board, 0 , 0 , 3 , 3 ) ;
if ( ! ret1) return false ;
bool ret2= isBoard ( board, 0 , 3 , 3 , 6 ) ;
if ( ! ret2) return false ;
bool ret3= isBoard ( board, 0 , 6 , 3 , 9 ) ;
if ( ! ret3) return false ;
bool ret4= isBoard ( board, 3 , 0 , 6 , 3 ) ;
if ( ! ret4) return false ;
bool ret5= isBoard ( board, 3 , 3 , 6 , 6 ) ;
if ( ! ret5) return false ;
bool ret6= isBoard ( board, 3 , 6 , 6 , 9 ) ;
if ( ! ret6) return false ;
bool ret7= isBoard ( board, 6 , 0 , 9 , 3 ) ;
if ( ! ret7) return false ;
bool ret8= isBoard ( board, 6 , 3 , 9 , 6 ) ;
if ( ! ret8) return false ;
bool ret9= isBoard ( board, 6 , 6 , 9 , 9 ) ;
if ( ! ret9) return false ;
return true ;
}