下面两个题目参考了戴同学的题解的思路。
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.
题目意思:判断某个不一定填满的九宫格是否是有效的,只需要考虑填了的数字。
方法:直接每行、每列、每个3*3单元进行判断即可,使用一个标记数组used[]
class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board) {
bool used[9];//是否使用过某数字的标记数组
for(int i=0; i<9; i++)
{
//判断每行
fill(used,used+9,false);
for(int j=0; j<9; j++)
{
if(isUsed(board[i][j],used))//判断每行
return false;//not valid
}
//判断每列
fill(used,used+9,false);
for(int j=0; j<9; j++)
{
if(isUsed(board[j][i],used))//判断每列
return false;//not valid
}
}
for(int i=0; i<9; i+=3)
{
for(int j=0; j<9; j+=3)
{
//判断每个3*3单元
fill(used,used+9,false);
for(int m=0; m<3; m++)
for(int n=0; n<3; n++)
if(isUsed(board[i+m][j+n],used))//判断每个3*3单元
return false;//not valid
}
}
return true;
}
//判断某个数字是否已经用过
bool isUsed(char c,bool used[])
{
if(c=='.')
return false;//
for(int i=0; i<9; i++)
if(used[c-'1']==true)
return true;
else
{
used[c-'1']=true;//此次使用,打上标记
return false;//没有使用过
}
}
};
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.
题目意思:输入未填满的九宫格,假设只有唯一解,将其填满即可。
方法:暴力枚举法,利用DFS进行即可。
class Solution {
public:
bool solveSudoku(vector<vector<char> > &board) {
for(int i=0; i<9; i++)
for(int j=0; j<9; j++)
{
if(board[i][j]=='.')
{
for(int k=0; k<9; k++)
{
board[i][j]=k+'1';//暴力试探
if(isValid(board,i,j) && solveSudoku(board))//递归调用,本质上就是DFS
return true;
else
board[i][j]='.';//恢复状态
}
return false;
}
}
return true;
}
bool isValid(vector<vector<char> > &board,int x,int y)
{
//对所在行判断
for(int j=0; j<9; j++)
if(j!=y && board[x][j]==board[x][y])
return false;
//对所在列判断
for(int i=0; i<9; i++)
if(i!=x && board[i][y]==board[x][y])
return false;
//对3*3单元进行判断
int x0=x/3*3,y0=y/3*3;//单元左上角格子坐标
for(int i=x0; i<x0+3; i++)
for(int j=y0; j<y0+3; j++)
if(i!=x && j!=y && board[i][j]==board[x][y])
return false;
return true;
}
};