Valid Sudoku

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.

思路:数独问题主要是说每行不能出现相同的数,且每列也不能出现相同的数,而且3*3的方格中也不能出现相同的数。那就按照这三个条件进行判断吧。这其中我使用set来作为辅助空间,因为set是不包含重复元素的,故可以用来进行判断。

class Solution {
public:
    bool isValidSudoku(vector<vector<char> > &board) {
        set<int> data1, data2, data3;
        for(int i=0;i<9;i++)
        {
            data1.clear();
            data2.clear();
            for(int j=0;j<9;j++)
            {
                if(board[i][j]!='.')
                {
                    if(data1.count(board[i][j])>0)
                        return false;
                    else
                        data1.insert(board[i][j]);
                }
                if(board[j][i]!='.')
                {
                    if(data2.count(board[j][i])>0)
                        return false;
                    else
                        data2.insert(board[j][i]);
                }
            }
        }
        for(int i=0;i<9;i+=3)
        {
            for(int j=0;j<9;j+=3)
            {
                data3.clear();
                for(int x=0;x<3;x++)
                {
                    for(int y=0;y<3;y++)
                    {
                        if(board[i+x][j+y]!='.')
                        {
                            if(data3.count(board[i+x][j+y])>0)
                                return false;
                            else
                                data3.insert(board[i+x][j+y]);
                        }
                    }
                }
            }
        }
        return true;
    }
};

 

 

posted @ 2014-04-09 20:50  Awy  阅读(136)  评论(0编辑  收藏  举报