問題描述:
Determine if a Sudoku is valid, according to: http://sudoku.com.au/TheRules.aspx
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.
判斷一個表是不是數獨表,什麼是數獨表呢,首先必須是9X9的表格,表格的每一行必須填入是1——9的互不重複的數字,每一列同樣也是,表格分9個3X3的小表格,這樣的小表格也必須填入1——9互不重複的數字。
針對本題,不完全的數獨表也默認是有效的,就是待填充的數獨表!
解題思路:
沒有什麼特別的算法,逐行逐列逐方塊判斷就行
class Solution
{
public:
bool isValidSudoku(vector<vector<char> > &board)
{
//特殊情況
if(board.size() == 0)
return false;
if(isRepeat(board,0,9,0,9,true))
{
if(isRepeat(board,0,9,0,9,false))
{
for(int i=0; i<9; i=i+3)
{
for(int j=0; j<9; j=j+3)
{
if(!isRepeat(board,i,i+3,j,j+3,true))
return false;
}
}
}
else
{
return false;
}
}
else
{
return false;
}
return true;
}
//rowOrColumn = true時逐行判斷,否則逐列判斷
bool isRepeat(vector<vector<char> > tempChar,int iFirst, int iEnd,int jFirst,int jEnd,bool rowOrColumn)
{
map<char,int> mp;
int setMapNull = 0;
if(rowOrColumn)
{
for (int i=iFirst; i<iEnd; i++)
{
for (int j=jFirst; j<jEnd; j++)
{
mp[tempChar[i][j]]++;
if (mp[tempChar[i][j]]>1&&tempChar[i][j]!='.')
{
return false;
}
setMapNull++;
}
if(setMapNull == 9)
{
mp.clear();
setMapNull = 0;
}
}
}
else
{
for (int j=jFirst; j<jEnd; j++)
{
for (int i=iFirst; i<iEnd; i++)
{
mp[tempChar[i][j]]++;
if (mp[tempChar[i][j]]>1&&tempChar[i][j]!='.')
{
return false;
}
setMapNull++;
}
if(setMapNull == 9)
{
mp.clear();
setMapNull = 0;
}
}
}
return true;
}
};