Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9
without repetition. - Each column must contain the digits
1-9
without repetition. - Each of the 9
3x3
sub-boxes of the grid must contain the digits1-9
without repetition.
A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
思考:先检查每一行,再检查每一列,最后检查9个子方块,时间复杂度为n2+n2+n2=O(n2)。
1 class Solution { 2 public: 3 bool isValidSudoku(vector<vector<char>>& board) { 4 int map[10] ={0}; 5 int i,j; 6 //row 7 for(i=0; i<9; i++) { 8 memset(map,0,10*sizeof(int)); 9 for(j=0;j<9;j++){ 10 if(board[i][j]=='.') continue; 11 if(map[board[i][j]-'0']) return false; 12 map[board[i][j]-'0'] = 1; 13 } 14 } 15 //column 16 for(j=0; j<9; j++) { 17 memset(map,0,10*sizeof(int)); 18 for(i=0; i<9; i++) { 19 if(board[i][j]=='.') continue; 20 if(map[board[i][j]-'0']) return false; 21 map[board[i][j]-'0'] = 1; 22 } 23 } 24 //3x3 subbox 25 for(i=0; i<9; i=i+3) { 26 for(j=0; j<9; j=j+3) { 27 memset(map, 0, 10*sizeof(int)); 28 for(int m=i; m<i+3; m++) { 29 for(int n=j; n<j+3; n++) { 30 if(board[m][n]=='.') continue; 31 if(map[board[m][n]-'0']) return false; 32 map[board[m][n]-'0'] = 1; 33 } 34 } 35 } 36 } 37 38 return true; 39 40 } 41 };