参考链接
http://blog.youkuaiyun.com/doc_sgl/article/details/13002461
题目描述
Valid Sudoku
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.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
bool isValidSudoku(vector<vector<char> > &board) {
// Note: The Solution object is instantiated only once.
vector<vector<bool>> rows(9, vector<bool>(9,false));
vector<vector<bool>> cols(9, vector<bool>(9,false));
vector<vector<bool>> blocks(9, vector<bool>(9,false));
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
{
if(board[i][j] == '.')continue;
int num = board[i][j] - '1';
if(rows[i][num] || cols[j][num] || blocks[i - i%3 + j/3][num])
return false;
rows[i][num] = cols[j][num] = blocks[i - i%3 + j/3][num] = true;
}
return true;
}
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.
class Solution {
public:
void solveSudoku(vector<vector<char> > &board) {
solveSudokuCore(board,0);
}
bool solveSudokuCore(vector<vector<char> > &board,int index)
{
if(index == 81) return true;
int m = index / 9, n = index%9;
if(board[m][n] != '.')
{
return solveSudokuCore(board,index+1);
}
// printvecvec(board,"board");
// system("pause");
set<char> leftnum;
for(int i = 1;i<10;i++)
leftnum.insert((char)(i+'0'));
for(int i = 0;i<9;i++)
{
if(board[m][i] != '.')
leftnum.erase(board[m][i]);
}
for(int i = 0;i<9;i++)
{
if(board[i][n] != '.')
leftnum.erase(board[i][n]);
}
int r = (m/3)*3;
int c = (n/3)*3;
for(int i = 0;i<3;i++)
for(int j = 0;j<3;j++)
{
if(r+i != m && c+j != n && board[r+i][c+j] != '.')
leftnum.erase(board[r+i][c+j]);
}
set<char>::iterator it;
/* printf("++%d,%d :",m,n);
for (it=leftnum.begin(); it!=leftnum.end(); ++it)
{
printf("%c ", *it);
}
printf("\n");
*/
for (it=leftnum.begin(); it!=leftnum.end(); ++it)
{
board[m][n] = *it;
//printf("%d,%d %c test\n",m,n,*it);
if(solveSudokuCore(board,index+1))
return true;
// else
// printf("%d,%d %c not ok\n",m,n,*it);
}
board[m][n] = '.';//////////////////////////////////////////////////////////////////
return false;
}
};