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 ‘.’.
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
bool isValidSudoku(vector<vector<char>> &board)
{
bool visited[9];
cout<<endl;
for (int i=0; i < 9; ++i)
{
fill(visited,visited+9,false);
for (int j=0; j < 9;++j) //检查行
{
if(!check(board[i][j],visited))
return false;
}
fill(visited,visited+9,false);
for (int j=0; j < 9;++j ) //检查列
{
if(!check(board[j][i],visited))
return false;
}
}
//检查九宫格的每个子九宫格
for (int i=0; i < 9; i+=3)
{
for (int j=0; j < 9; j+=3)
{
fill(visited,visited+9,false);
for (int k=0; k < 9 ; ++k)
{
bool chk=check(board[i+k/3][j+k%3],visited);
if (!chk)
{
return false;
}
}
}
}
return true;
}
private:
bool check(char ch, bool visited[9])
{
if (ch == '.')
return true;
if (visited[ch - '1'])
return false;
return visited[ch - '1'] = true;
}
};
int main()
{
vector<vector<char>> board = {{'5','3','.','.','7','.','.','.','.'},{'6','.','.','1','9','5','.','.','.'},
{'.','9','8','.','.','.','.','6','.'},{'8','.','.','.','6','.','.','.','3'},
{'4','.','.','8','.','3','.','.','1'},{'7','.','.','.','2','.','.','.','6'},
{'.','6','.','.','.','.','2','8','.'},{'.','.','.','4','1','9','.','.','5'},
{'.','.','.','.','8','.','.','7','9'}
};
for(auto it=board.cbegin(); it != board.cend(); ++it)
{
for(auto iter= (*it).cbegin(); iter != (*it).cend(); ++iter)
cout<<*iter<<" ";
cout<<endl;
}
cout<<endl;
Solution solution;
bool result = solution.isValidSudoku(board);
cout<<boolalpha<<result<<endl;
return 0;
}