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 ‘.‘
.
注意这里的有效数独并非指的是可以解出来,只要存在的数满足数独的条件就可以了。
原理很简单,但是判定在同一个blocks的时候出了点问题,没想到判定方法,看了下别人的,很精妙,代码如下:
1 class Solution { 2 public: 3 bool isValidSudoku(vector<vector<char>>& board) { 4 vector<vector<bool>> rowValid(9, vector<bool>(9, true)); 5 vector<vector<bool>> colValid(9, vector<bool>(9, true)); 6 vector<vector<bool>> blockValid(9, vector<bool>(9, true)); 7 for (int i = 0; i < 9; ++i){ 8 for(int j = 0; j < 9; ++j){ 9 if(board[i][j] == ‘.‘) continue; 10 int num = board[i][j] - ‘1‘;//注意这里是减‘1‘ 11 if(!rowValid[i][num] || !colValid[j][num] || !blockValid[i-i%3+j/3][num])//判定在一个block中的代码很巧妙,i-i%3制造了一个高度为3的阶梯,然后j/3正好可以将这个阶梯填满 12 return false; 13 rowValid[i][num] = colValid[j][num] = blockValid[i-i%3+j/3][num] = false; 14 } 15 } 16 return true; 17 } 18 };
时间: 2024-10-09 13:55:54