下面兩個題目參考了戴同學的題解的思路。
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;
}
};