问题描述:
https://oj.leetcode.com/problems/valid-sudoku/点击打开链接
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 '.'
数独: 9 * 9 的方格,分成9个3 * 3的方格。
数独合法性:
1. 每行都[1, 9]中的数字最多只出现一次
2. 每列中的[1, 9]中的数字最多只出现一次
3. 每个子块(3 * 3)中[1, 9]中的数字最多只出现一次
下面链接有详细说明
http://sudoku.com.au/TheRules.aspx点击打开链接
问题分析:
分别给出三种情况合法性的检测,然后逐行、逐列、逐子块的方式进行检测。
示例代码:
bool isValidSudoku(vector<vector<char> > &board)
{
int n = board.size();
if (n != 9) return false;
n = board[0].size();
if (n != 9) return false;
for (int i = 0; i < 9; i++)
{
if (!(validRow(board, i) && validColum(board, i) && validSubset(board, i)))
return false;
}
return true;
}
bool validRow(vector<vector<char> > &board, int n)
{
char count[10] = { 0 };
for (int i = 0; i < 9; i++)
{
if (board[n][i] == '.') continue;
if (++count[board[n][i] - '0'] > 1 ) return false;
}
return true;
}
bool validColum(vector<vector<char> > &board, int n)
{
char count[10] = { 0 };
for (int i = 0; i < 9; i++)
{
if (board[i][n] == '.') continue;
if (++count[board[i][n] - '0'] > 1 ) return false;
}
return true;
}
bool validSubset(vector<vector<char> > &board, int n)
{
int x, y;
char count[10] = { 0 };
x = (n / 3) * 3; y = (n % 3) * 3;
for (int i = x; i < x + 3; i++)
{
for (int j = y; j < y + 3; j++)
{
if (board[i][j] == '.') continue;
if (++count[board[i][j] - '0'] > 1 ) return false;
}
}
return true;
}