class Solution {
public:
bool isValidSudoku(vector
>& board,int rowIndex,int colIndex) {
int flags[9];
memset( flags, 0, sizeof(flags) );
//行判断
for(int j=0;j<9;j++)
{
if( board[rowIndex][j] =='.' )
continue;
if( flags[board[rowIndex][j]-'1'] == 1 )
return false;
else
flags[board[rowIndex][j]-'1'] = 1 ;
}
//列判断
memset( flags, 0, sizeof(flags) );
for(int j=0;j<9;j++)
{
if( board[j][colIndex] =='.' )
continue;
if( flags[board[j][colIndex]-'1'] == 1 )
return false;
else
flags[board[j][colIndex]-'1'] = 1 ;
}
//矩形判断
memset( flags, 0, sizeof(flags) );
for(int i=(rowIndex/3)*3;i<(rowIndex/3)*3+3;i++)
{
for(int j=(colIndex/3)*3;j<(colIndex/3)*3+3;j++)
{
if( board[i][j] == '.' )
continue;
if(flags[board[i][j]-'1'] == 1)
return false;
else
flags[board[i][j]-'1'] = 1 ;
}
}
return true;
}
void solveSudoku(vector
>& board)
{
isSolveSudoku(board);
}
bool isSolveSudoku(vector
>& board) { for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { if(board[i][j]=='.') { for(int k=1;k<=9;k++) { board[i][j]=k+'0'; if( isValidSudoku(board,i,j) && isSolveSudoku(board) ) return true; board[i][j]='.'; //这里千万不能丢,如果这里丢了,那么这层递归退出后但是你却填充了数9,退到外层递归循环k值,到时候这里是一个9,其实应该是点。 } return false;//不要忘记了 } } } return true; } };
leetcode 37:Sudoku Solver
最新推荐文章于 2021-10-02 00:35:03 发布