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.
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Use array to mark the access of elements in board. For each element in board, check three arrays in the same time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isValidSudoku(vector<vector<char>>& board) { | |
vector<vector<int> > flag(27, vector<int>(9, 0)); | |
for(int row=0; row<9; row++){ | |
for(int col=0; col<9; col++){ | |
char c = board[row][col]; | |
if(c=='.') | |
continue; | |
int n = c-'1'; | |
// row flag | |
if(flag[0+row][n]==0) | |
flag[0+row][n]=1; | |
else | |
return false; | |
// col flag | |
if(flag[9+col][n]==0) | |
flag[9+col][n]=1; | |
else | |
return false; | |
// chunk flag | |
int idx=(ceil((row+1)/3.0)-1)*3+(ceil((col+1)/3.0)-1); | |
if(flag[18+idx][n]==0) | |
flag[18+idx][n]=1; | |
else | |
return false; | |
} | |
} | |
return true; | |
} | |
}; |
No comments:
Post a Comment