Leetcode 细节实现 Valid Sudoku

Valid Sudoku

  Total Accepted: 13142  Total Submissions: 47070 My Submissions

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.



题意:检查一个给定的数独是否是合理的,该数独可能可有些单元是空白的
思路:
检查每一行,第一列,每一个小方块中是否出现重复数字
可用一个大小为 9的数组表示某个数字是否出现过
复杂度:O(n^2)

bool isExist[9];


bool check(const vector<vector<char> >& board, int i, int j){
	if(board[i][j] != '.') {
		if (isExist[board[i][j] - '1']) return false;
		else return isExist[board[i][j] - '1'] = true;
	}
	return true;
};
bool isValidSudoku(const vector<vector<char> >& board){
	//检查行
	for(int i = 0; i < 9; ++i){
		memset(isExist, false, sizeof(isExist));
		for(int j = 0; j < 9; ++j){
			if(!check(board, i, j)) return false;
		}
	}
	//检查列
	for(int j = 0; j < 9; ++j){
		memset(isExist, false, sizeof(isExist));
		for(int i = 0; i < 9; ++i){
			if(!check(board, i, j)) return false;
		}
	}
	//检查小方块
	for(int k = 0; k < 9; ++k){
		memset(isExist, false, sizeof(isExist));
		for(int i = 0; i < 3; ++i){
			for(int j = 0; j < 3; ++j){
				int ii = k % 3 * 3 + i;
				int jj = k / 3 * 3 + j;
				if(!check(board, ii, jj)) return false;
			}
		}
	}
	return true;
}



你可能感兴趣的:(Leetcode 细节实现 Valid Sudoku)