Valid Sudoku

-----QUESTION-----

Determine if a Sudoku is valid, according to: Sudoku Puzzles - TheRules.

The Sudoku board could be partially filled, where empty cells are filled with the character'.'.

Valid <wbr>Sudoku

A partially filled sudoku which is valid.

-----SOLUTION-----

class Solution {
public:
    bool isValidSudoku(vector<vector<char> > &board) {
        vector<bool> flag(board.size()+1, false);
        //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]-'0']) return false;
                flag[board[i][j]-'0'] = true;
            }
            flag.assign(board.size()+1,false);
        }
        flag.assign(board.size()+1,false);
        //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]-'0']) return false;
                flag[board[i][j]-'0'] = true;
            }
            flag.assign(board.size()+1,false);
        }
        flag.assign(board.size()+1,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]-'0']) return false;
                        flag[board[i+m][j+n]-'0'] = true;
                    }
                }
                flag.assign(board.size()+1,false);
            }
        }
        return true;
    }
};

如果没有'.',那么我们可以用以下的方法判断是否valid

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;
}
参数是某一行,某一列,或是某一个small square的9个元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值