码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 细节实现

时间:2014-09-07 13:33:35      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   ar   for   2014   

Valid Sudoku

 Total Accepted: 13142 Total Submissions: 47070My 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 ‘.‘.

bubuko.com,布布扣

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 细节实现

标签:style   blog   http   color   os   io   ar   for   2014   

原文地址:http://blog.csdn.net/zhengsenlie/article/details/39119275

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!