题解 | #数独#

数独

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

回溯

class Solution {
public:
    int Count;
    bool row[10][10];
    bool column[10][10];
    bool subsquare[10][10];
    struct Node{
        int x;
        int y;
        Node(int xx, int yy) :x(xx), y(yy) {}
        Node() {}
    }Points[100];
    int Judge(int i, int j){ //规定每个小九宫格的号码
        return ((i - 1) / 3 )* 3 + (j - 1) / 3 + 1;
    /*
     1 2 3
     4 5 6
     7 8 9

     1+3*0 2+3*0 3+3*0
     1+3*1 2+3*1 3+3*1
     1+3*2 2+3*2 3+3*2
    */
    }
    bool helper(int n, vector<vector<char>> & board){
        if (n > Count) return true;
        //每个空点都有1-9九种可能
        for(int i = 1; i <= 9; i++){
            if(!row[Points[n].x][i] && !column[i][Points[n].y] && !subsquare[Judge(Points[n].x, Points[n].y)][i]){
                row[Points[n].x][i] = true;
                column[i][Points[n].y] = true;
                subsquare[Judge(Points[n].x, Points[n].y)][i] = true;
                board[Points[n].x - 1][Points[n].y - 1] = i + '0';
                if(helper(n + 1, board)) return true;
                row[Points[n].x][i] = false;
                column[i][Points[n].y] = false;
                subsquare[Judge(Points[n].x, Points[n].y)][i] = false;
            }
        }
        return false;
    }
    void solveSudoku(vector<vector<char> > &board) {
        memset(row, false, sizeof(row));
        memset(column, false, sizeof(column));
        memset(subsquare, false, sizeof(subsquare));
        for(int i = 1; i <= 9; i ++){
            for(int j = 1; j <= 9; j ++){
                if(board[i - 1][j - 1] == '.'){
                    Count ++;
                    Points[Count].x = i;
                    Points[Count].y = j;
                }else{
                    int val = board[i - 1][j - 1] - '0';
                    row[i][val] = true;
                    column[val][j] = true;
                    subsquare[Judge(i, j)][val] = true;
                }
            }
        }
        helper(1, board);
    }
};
全部评论

相关推荐

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