题目:
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'
.
You may assume that there will be only one unique solution.
A sudoku puzzle...
...and its solution numbers marked in red.
思路:
利用NP的思想完成,为了加快运算速度,我利用了三个数组来保存横列、纵列、方形中的数字重复。
代码:
class Solution {
public:
bool num[3][9][9];
void solveSudoku(vector<vector<char> > &board) {
for(int i=0;i<3;i++)
{
for(int j=0;j<9;j++)
{
for(int k=0;k<9;k++)
{
num[i][j][k]=true;
}
}
}
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
if(isInteger(board[i][j]))
{
num[0][i][board[i][j]-'1'] = false;
num[1][j][board[i][j]-'1'] = false;
num[2][i/3*3+j/3][board[i][j]-'1'] = false;
}
}
}
fillValidSudoku(0,0,board);
}
bool fillValidSudoku(int i,int j,vector<vector<char> > &board)
{
if(j==9)
{
i++;
j=0;
}
if(i==9&&j==0)
{
return true;
}
else if(isInteger(board[i][j]))
{
return fillValidSudoku(i,j+1,board);
}
else
{
for(int k=1;k<=9;k++)
{
if(num[0][i][k-1]&&num[1][j][k-1]&&num[2][i/3*3+j/3][k-1])
{
board[i][j]='0'+k;
num[0][i][k-1] = false;
num[1][j][k-1] = false;
num[2][i/3*3+j/3][k-1] = false;
if(fillValidSudoku(i,j+1,board))
{
return true;
}
else
{
num[0][i][k-1] = true;
num[1][j][k-1] = true;
num[2][i/3*3+j/3][k-1] = true;
board[i][j]='.';
}
}
}
return false;
}
}
bool isInteger(char c)
{
if(c-'0'>=1&&c-'0'<=9)
{
return true;
}
return false;
}
};