题解 | #数独#

数独

http://www.nowcoder.com/practice/5e6c424b82224b85b64f28fd85761280

class Solution {
public:
    vector<vector<char> > ans;
    bool check(vector<vector<char> > &board,int row,int col,char val){
        int startrow = row / 3 * 3,startcol = col / 3 * 3;
        for(int i =  startrow;i <= startrow + 2;++i)
            for(int j = startcol;j <= startcol + 2;++j)
                if(board[i][j] == val)
                    return false;
        for(int i = 0;i < board.size();++i)
            if(board[i][col] == val)
                return false;
        for(int i = 0;i < board[0].size();++i)
            if(board[row][i] == val)
                return false;
        return true;
    }
    void back(vector<vector<char> > &board,int row,int col){
        if(board[row][col] == '.'){
            for(int i = 1;i <= 9;++i){
                if(check(board,row,col,i + '0')){
                    board[row][col] = i + '0';
                    if(col + 1 < board[row].size())
                        back(board,row,col + 1);
                    else if(row + 1 < board.size())
                        back(board,row + 1,0);
                    else
                        ans = board;
                    board[row][col] = '.';
                }
            }
        }
        else{
            if(col + 1 < board[row].size())
                back(board,row,col + 1);
            else if(row + 1 < board.size())
                back(board,row + 1,0);
            else
                ans = board;
        }
    }
    void solveSudoku(vector<vector<char> > &board) {
        back(board,0,0);
        board = ans;
    }
};
全部评论

相关推荐

无情咸鱼王的秋招日记之薛定谔的Offer:好拒信,偷了,希望有机会用到
点赞 评论 收藏
分享
10-31 14:54
已编辑
门头沟学院 算法工程师
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务