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.
判断一个数独是否合法。一个合法的数独要求:每行、每列、9个小九宫格中都只能填充1~9九个数字各一次。
class Solution { public: bool isValidSudoku(vector<vector<char> > &board) { vector<vector<bool> > rows(9, vector<bool>(9, false)); vector<vector<bool> > cols(9, vector<bool>(9, false)); vector<vector<bool> > blocks(9, vector<bool>(9, false)); for(int i=0; i<9; i++){ for(int j=0; j<9; j++){ if(board[i][j]==‘.‘)continue; //判断行 if(rows[i][board[i][j]-‘0‘-1])return false; else rows[i][board[i][j]-‘0‘-1]=true; //判断列 if(cols[j][board[i][j]-‘0‘-1])return false; else cols[j][board[i][j]-‘0‘-1]=true; //判断block if(blocks[i/3*3+j/3][board[i][j]-‘0‘-1])return false; //注意block索引号的计算 else blocks[i/3*3+j/3][board[i][j]-‘0‘-1]=true; } } return true; } };
LeetCode: Valid Sudoku [035],布布扣,bubuko.com
原文地址:http://blog.csdn.net/harryhuang1990/article/details/26239443