leetcode - Valid Sudoku
2017-06-09 20:26
267 查看
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
![](http://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png)
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.
The Sudoku board could be partially filled, where empty cells are filled with the character
'.'.
![](http://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png)
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 isValidSudoku(std::vector<std::vector<char> > &board) { int rows = board.size(); int cols = board[0].size(); int mask=0; int val; for(int i=0;i<rows;i++){ mask=0; for(int j=0;j<cols;j++){ if(board[i][j]!='.'){ int val = (int)(board[i][j]-'0'); if(mask & (1<<val)) return false; else mask |= (1<<val); } } } //rows are checked for(int j=0;j<cols;j++){ mask=0; for(int i=0;i<rows;i++){ if(board[i][j]!='.'){ int val = (int)(board[i][j]-'0'); if(mask & (1<<val)) return false; else mask |= (1<<val); } } } //cols are checked for(int i=0;i<rows;i+=3) { for(int j=0;j<cols;j+=3) { mask=0; for(int k=i;k<=i+2;k++) { for(int l=j;l<=j+2;l++) { if(board[k][l]!='.'){ val = (int)(board[k][l]-'0'); if(mask&(1<<val)) return false; else mask|=(1<<val); } } } } } return true; } };
相关文章推荐
- Leetcode[36]-Valid Sudoku
- Leetcode: Valid Sudoku
- Leetcode: 36. Valid Sudoku
- 【LeetCode】C# 36、Valid Sudoku
- LeetCode -- Valid Sudoku
- [Leetcode] valid sudoku 有效数独
- Leetcode-Valid Sudoku
- LeetCode:Valid Sudoku
- leetcode-36 Valid Sudoku
- leetcode先刷_Valid Sudoku
- leetcode题解-36. Valid Sudoku
- leetcode Valid Sudoku
- LeetCode - 36 - Valid Sudoku
- LeetCode36——Valid Sudoku
- [LeetCode]题解(python):036-Valid Sudoku
- 【C++】【LeetCode】36. Valid Sudoku
- LeetCode:Valid Sudoku
- leetcode--Valid Sudoku
- LeetCode Online Judge 题目C# 练习 - Valid Sudoku
- Valid Sudoku :from LeetCode