描述
2.1.14 Valid Sudoku
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules
http://sudoku.com.au/TheRules.aspx .
The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’.
分析
九宫格规则
很容易得到3个规则:
每一行只能出现1~9一次;
每一列只能出现1~9一次;
每个3×3子区域只能出现1~9一次(子区域之间没有交叉,也就是一共有9个子区域)
代码
/*
date: 2018/3/16 10:57
des:
2.1.14 Valid Sudoku(有效 九宫格)
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules
http://sudoku.com.au/TheRules.aspx .
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
analysis:
验证数独是否有效,根据 Sudoku Puzzles 规则http://sudoku.com.au/TheRules.aspx 空的填‘.’
SalidSudoku 规则
1、每一行9个格子1-9出现一次
2、每一列9个格子1-9出现一次
3、每个3*3的格子(不交叉) 1-9 出现一次
按照规则依次检查 二维数组遍历
思考如何产生一个有效的九宫格?
*/
#include "type.h"
typedef vector<vector<char>> Sudoku;
char arrSudoku[9][9]={
{'5', '.', '3', '.', '7', '.', '.', '.', '.'},
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
{'.', '9', '8', '.', '.', '.', '.', '6', '.'},
{'8', '.', '.', '.', '6', '.', '.', '.', '3'},
{'4', '.', '.', '8', '.', '3', '.', '.', '1'},
{'7', '.', '4', '.', '2', '.', '.', '.', '6'},
{'.', '6', '.', '.', '.', '.', '2', '8', '.'},
{'.', '.', '.', '4', '1', '9', '.', '.', '5'},
{'.', '.', '.', '.', '8', '.', '.', '7', '9'},
};
int columnSudoku = sizeof(arrSudoku)/sizeof(arrSudoku[0]);
int rowSudoku = sizeof(arrSudoku[0])/sizeof(char);
Sudoku vecSudoku( 9,vector<char>(9,0) );
bool isValidSudoku()
{
//初始化vector
for (int i=0; i<rowSudoku; i++)
{
//vecSudoku[i](arrSudoku[i],arrSudoku[i]+columnSudoku);
vecSudoku[i] = vector<char>(arrSudoku[i],arrSudoku[i]+columnSudoku);
}
bitset<9> isUsed;
isUsed.reset();
//验证
for(int i=0; i<columnSudoku; i++)//行
{
isUsed.reset();
for (int j=0; j<rowSudoku; j++)
{
int index = vecSudoku[i][j]=='.' ? -1 : vecSudoku[i][j]-'0';
if (index<0)
continue;
if (isUsed.test(index-1))
return false;
else
isUsed.set(index-1);
}
}
for (int i=0; i<rowSudoku; i++)//列
{
isUsed.reset();
for (int j=0; j<columnSudoku; j++)
{
int index = vecSudoku[j][i]=='.' ? -1 : vecSudoku[j][i]-'0';
if (index<0)
continue;
if (isUsed.test(index-1))
return false;
else
isUsed.set(index-1);
}
}
//3*3 9个格子
for (int r=0; r<3; r++ )
{
for (int c=0; c<3; c++)
{
isUsed.reset();
for (int i=r*3; i<3+r*3; i++)
{
for (int j=c*3; j<3+c*3; j++)
{
int index = vecSudoku[i][j]=='.' ? -1 : vecSudoku[i][j]-'0';
if (index<0)
continue;
if (isUsed.test(index-1))
return false;
else
isUsed.set(index-1);
}
}
}
}
return true;
}