题解 | #数独#

数独

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;
    }
};
全部评论

相关推荐

头像
11-18 16:08
福州大学 Java
影流之主:干10年不被裁,我就能拿别人一年的钱了,日子有盼头了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务