您的位置:首页 > 编程语言 > C语言/C++

leetcode #36 in cpp.

2016-05-26 00:27 309 查看
The question is to determine a Sudoku is valid. 

Solution:  if a Sudoku is valid, each row, each column and each block in it would not have duplicates.Thus we have 3 loops to check if each condition is satisfied. We can use hashmap to check if there are duplicates.

I find out using loops to check each block using a hash map of size 9 is quite frustrating. And I don't want to use 9 hash maps for 9 blocks. Thus I write a recurrence function to check the block. Each recurrent call check one block.  

Code: 

class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
if(board.empty()) return 0;
return check_row(board) && check_col(board) && check_block(board,0,0,0);
}
bool check_row(vector<vector<char>> board){
for(int row = 0; row < board.size(); row++){
map<char,int> mapp;
for(int col = 0; col < board[0].size(); col ++){
if(board[row][col] == '.') continue;
if(mapp.find(board[row][col]) != mapp.end()) return 0;
else mapp[board[row][col]] = 1;
}
}
return 1;

}
bool check_col(vector<vector<char>> board){
for(int col = 0; col < board[0].size(); col++){
map<char,int> mapp;
for(int row = 0; row < board.size(); row ++){
if(board[row][col] == '.') continue;
if(mapp.find(board[row][col]) != mapp.end()) return 0;
else mapp[board[row][col]] = 1;
}
}
return 1;

}
bool check_block(vector<vector<char>> board,int start_row, int start_col,int count){
if(count == 9) return 1;
int row_upper = start_row + 3;//range of current block
int col_upper = start_col + 3;//range of current block
int row = start_row;
int col = start_col;
map<char, int> mapp;
//check current block
for(; row < row_upper; row++){
for(;col < col_upper; col++){
if(board[row][col] == '.') continue;
if(mapp.find(board[row][col])!=mapp.end()) return 0;
mapp[board[row][col]] = 1;
}
col = start_col;//get to the next row and initial column
}
if(col_upper == 9){//the next block will start at the next row+3 with col = 0
start_col = 0;
start_row += 3;
}else{//next block is still in the same rows but with different start_col
start_col = col_upper;
}
return check_block(board, start_row, start_col, count + 1);

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp leetcode