描述
Determine if a Sudoku is valid, according to: Sudoku Puzzles - e Ruleshttp://sudoku.com.au/TheRules.aspx .
Determine if a Sudoku is valid, according to: Sudoku Puzzles - e Ruleshttp://sudoku.com.au/TheRules.aspx .
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
#include<iostream>
using namespace std;
const int COL = 9;
const int SUB = 3;
bool ValidSudoku(int a[][COL], int row)
{
bool flag = false;
for (int i = 0; i < row; i++)//处理行
{
bool temp[COL] = { false };
for (int j = 0; j < COL; j++)
{
if (a[i][j] != 0)
{
if (!temp[a[i][j] - 1])
temp[a[i][j] - 1] = true;
else
return flag;
}
}
}
//
for (int j = 0; j < COL; j++)//处理列
{
bool temp[COL] = { false };
for (int i = 0; i < row; i++)
{
if (a[i][j] != 0)
{
if (!temp[a[i][j] - 1])
temp[a[i][j] - 1] = true;
else
return flag;
}
}
}
//处理每个子宫格
for (int i = 0; i < row - 2; i++)
{
for (int j = 0; j < COL - 2; j++)
{
for (int k1 = i; k1 < i + 3; k1++)
{
bool temp[9] = { false };
for (int k2 = j; k2 < j + 3; k2++)
{
if (a[k1][k2] != 0)
{
if (!temp[a[k1][k2] - 1])
temp[a[k1][k2] - 1] = true;
else
return flag;
}
}
}
//
for (int k1 = j; k1 < j + 3; k1++)
{
bool temp[9] = { false };
for (int k2 = i; k2 < i + 3; k2++)
{
if (a[k2][k1] != 0)
{
if (!temp[a[k2][k1] - 1])
temp[a[k2][k1] - 1] = true;
else
return flag;
}
}
}
//
}
}
flag = true;
return flag;
}
int main()
{
int a[COL][COL] =
{
{ 5, 3, 0, 0, 7, 0, 0, 0, 0 }, { 6, 0, 0, 1, 9, 5, 0, 0, 0 }, { 0, 9, 8, 0, 0, 0, 0, 6, 0 },
{ 8, 0, 0, 0, 6, 0, 0, 0, 3 }, { 4, 0, 0, 8, 0, 3, 0, 0, 1 }, { 7, 0, 0, 0, 2, 0, 0, 0, 6 },
{ 0, 6, 0, 0, 0, 0, 2, 8, 0 }, { 0, 0, 0, 4, 1, 9, 0, 0, 5 }, { 0, 0, 0, 0, 8, 0, 0, 7, 9 },
};
bool flag = ValidSudoku(a, COL);
if (flag)
cout << "this is valid sudoku!" << endl;
}