36. Valid Sudoku (Array; HashTable)

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.

class Solution {
public:
    bool isValidSudoku(vector<vector<char> > &board) {
        vector<bool> flag(9, false); //indicate the appearance of 1,2,..., 9
        //check line
        for(int i = 0; i<9; i++)
        {
            for(int j = 0; j<9; j++)
            {
                if(board[i][j]=='.') continue;
                if(flag[board[i][j]-'1']) return false;
                flag[board[i][j]-'1'] = true;
            }
            flag.assign(board.size(),false); //reset the vector
        }
   
        //check column
        for(int j = 0; j<9; j++)
        {
            for(int i = 0; i<9; i++)
            {
                if(board[i][j]=='.') continue;
                if(flag[board[i][j]-'1']) return false;
                flag[board[i][j]-'1'] = true;
            }
            flag.assign(board.size(),false);
        }
   
        //check small square
        for(int i = 0; i < 9; i+=3){
            for(int j = 0; j <9; j+=3){
                for(int m = 0; m < 3; m++){
                    for(int n = 0; n < 3; n++){
                        if(board[i+m][j+n]=='.') continue;
                        if(flag[board[i+m][j+n]-'1']) return false;
                        flag[board[i+m][j+n]-'1'] = true;
                    }
                }
                flag.assign(board.size(),false);
            }
        }
        return true;
    }
};

 如果没有'.',那么我们可以用以下的方法判断是否valid (参数是某一行,某一列,或是某一个small square的9个元素)

bool check(vector<int> v) {
    sort(v.begin(), v.end());
    for (int i = 0; i < (int)v.size(); ++i) {
        if (v[i] != i + 1) {
            return false;
        }
    }
    return true;
}
原文地址:https://www.cnblogs.com/qionglouyuyu/p/4857030.html