请判定一个数独是否有效。
该数独可能只填充了部分数字,其中缺少的数字用 . 表示。
注意事项:
一个合法的数独(仅部分填充)并不一定是可解的。我们仅需使填充的空格有效即可。
说明:
什么是 数独?
http://sudoku.com.au/TheRules.aspx
http://baike.baidu.com/subview/961/10842669.htm
样例:
The following partially filed sudoku is valid.
#ifndef C389_H
#define C389_H
#include<iostream>
#include<vector>
#include<map>
using namespace std;
class Solution {
public:
/*
* @param board: the board
* @return: whether the Sudoku is valid
*/
bool isValidSudoku(vector<vector<char>> &board) {
// write your code here
int m = board.size();
int n = board[0].size();
map<char, int> count;
for (int i = 0; i < m; ++i)
{
count.clear();
for (int j = 0; j < n; ++j)
{
if (isdigit(board[i][j]))
{
if (count.find(board[i][j]) == count.end())
{
count[board[i][j]]++;
}
else
{
return false;
break;
}
}
}
}
for (int j = 0; j < n; ++j)
{
count.clear();
for (int i = 0; i < m; ++i)
{
if (isdigit(board[i][j]))
{
if (count.find(board[i][j]) == count.end())
{
count[board[i][j]]++;
}
else
{
return false;
break;
}
}
}
}
vector<vector<int>> dir{ { 0, 0 }, { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 }, { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 } };
vector<vector<int>> center{ { 1, 1 }, { 1, 4 }, { 1, 7 }, { 4, 1 }, { 4, 4 }, { 4, 7 }, { 7, 1 }, { 7, 4 }, { 7, 7 } };
for (auto c : center)
{
count.clear();
for (auto t : dir)
{
int x = c[0] + t[0];
int y = c[1] + t[1];
if (isdigit(board[x][y]))
{
if (count.find(board[x][y]) == count.end())
{
count[board[x][y]]++;
}
else
{
return false;
break;
}
}
}
}
return true;
}
};
#endif