Valid Sudoku

难度:1

个人总结:傻傻地写错两个符号,1Y失败

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.

由于输入一定是9*9的数组,所以也没有什么要注意的地方

class Solution 
{
public:
	bool row(vector<char> &r)
	{
		int opt=0;
		for(int i=0;i<r.size();i++)
		{
			if(r[i] == '.')	continue;
			if(opt&(1<<(r[i]-'0'-1)))		return false;
			opt+=(1<<(r[i]-'0'-1));
		}
		return true;
	}
	bool col_check(vector<vector<char> > &board, int col)
	{
		int opt=0;
		for(int i=0;i<board.size();i++)
		{
			if(board[i][col] == '.')	continue;
			if(opt&(1<<(board[i][col]-'0'-1)))		return false;
			opt+=(1<<(board[i][col]-'0'-1));
		}
		return true;
	}
	bool center_check(vector<vector<char> > &board, int x, int y)
	{
		int dir[8][2]={{1,0},{1,-1},{1,1},{-1,-1},{-1,1},{-1,0},{0,1},{0,-1}};
		int opt=0;
		opt+=(1<<(board[x][y]-'0'-1));
		for(int i=0;i<8;i++)
		{
			if(board[x+dir[i][0]][y+dir[i][1]] == '.')	continue;
			if(opt&(1<<(board[x+dir[i][0]][y+dir[i][1]]-'0'-1)))	return false;
			opt+=(1<<(board[x+dir[i][0]][y+dir[i][1]]-'0'-1));
		}
		return true;
	}
    bool isValidSudoku(vector<vector<char> > &board) 
	{
		for(int i=0;i<board.size();i++)
		{
			if(!row(board[i]))	return false;
		}
		if(board.size()>0&&board[0].size()>0)
		{
			for(int i=0;i<board[0].size();i++)
			{
				if(!col_check(board,i))	return false;
			}
		}
		int center[9][2]={{1, 1}, {1, 4}, {1, 7}, {4, 1}, {4, 4}, {4, 7}, {7, 1}, {7, 4}, {7, 7} };
		for(int i=0;i<9;i++)
		{
			if(!center_check(board,center[i][0],center[i][1]))	return false;
		}
		return true;
    }
};


你可能感兴趣的:(Valid Sudoku)