您的位置:首页 > 其它

[leetcode]Valid Sudoku

2014-02-25 11:01 295 查看


Valid Sudoku

Total Accepted: 4716 Total
Submissions: 17442My Submissions

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
'.'
.



A partially filled sudoku which is valid.

Note:

A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

本题一开始 看不太懂题目,其实就是检查每行,每列 每个格子 是否有重复的值或者 不在范围内的,遍历一遍就可以

class Solution {
public:
bool AnyRect(vector<vector<char>> &board, int x1,int y1,int x2,int y2){
vector<int> map(256,0);
for(int row=x1; row<=x2; row ++){
for(int col=y1; col <=y2; col ++){
int ch=board[row][col];
if(ch <= '9' && ch >='1'){
if(map[ch]!=0)
return false;
map[ch]++;
}
else if(ch!='.')
return false;
}
}
return true;
}

bool checkRowAndCol(vector<vector<char> > &board){
for(int col=0; col<9; col++){ //检查每行
if(AnyRect(board, 0,col,8,col)==false)
return false;
}
for(int row=0; row<9; row++){ //检查每列
if(AnyRect(board,row,0,row,8)==false)
return false;
}
return true;
}

bool checkGrid(vector<vector<char>> &board){
for(int gridrow=0; gridrow<3; gridrow++){
for(int gridcol=0; gridcol<3; gridcol++){
int row1=gridrow*3;
int row2=row1+2;
int col1=gridcol*3;
int col2=col1+2;
if(AnyRect(board,row1,col1,row2,col2)==false)
return false;
}
}
return true;
}
bool isValidSudoku(vector<vector<char> > &board) {
return checkRowAndCol(board) && checkGrid(board);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: