row : there exists only 1-9, no duplicate
column: there exists only 1-9, no duplicate
block : there exists only 1-9, no duplicate
2. Implementation
// Time:O(3* n^2), Space:O(n)
public boolean isValidSudoku( char[][] board )
{
// validate the input
if ( board == null || board.length == 0 || board[0].length == 0 )
return false;
// check row
for ( int i = 0 ; i < board.length;i++ )
{
boolean[] digit = new boolean[9];
for ( int j = 0 ; j < board[0].length; j++ )
{
// NOTE: EMPTY is allowed
if ( board[i][j] != '.' )
{
if ( digit[(int)(board[i][j] - '0')-1] )
{
return false;
}
//else
//{
digit[(int)(board[i][j] - '0')-1] = true;
//}
}
}
}
// check column
for ( int j = 0 ; j < board[0].length;j++ )
{
boolean[] digit = new boolean[9];
for ( int i = 0 ; i < board.length; i++ )
{
// NOTE: EMPTY is allowed
if ( board[i][j] != '.' )
{
if ( digit[(int)(board[i][j] - '0')-1] )
{
return false;
}
//else
//{
digit[(int)(board[i][j] - '0')-1] = true;
//}
}
}
}
// check block
// 0 - 012 1 - 345 2 - 678
// 3 4 5
// 6 7 8
for ( int k = 0 ; k < 9; k++ )
{
boolean[] digit = new boolean[9];
//for (int i = (k%3)*3; i < (k%3)*3+3;i++ )
for (int j = (k/3)*3; j < (k/3)*3+3; j++ )
{
//for (int j = (k/3)*3; j < (k/3)*3+3; j++ )
for (int i = (k%3)*3; i < (k%3)*3+3;i++ )
{
// NOTE: EMPTY is allowed
if ( board[i][j] != '.' )
{
if ( digit[(int)(board[i][j] - '0')-1] )
{
return false;
}
//else
//{
digit[(int)(board[i][j] - '0')-1] = true;
//}
}
}
}
}
return true;
}
3. Similar OnesSudoku solver
No comments:
Post a Comment