首页 > 其他 > 详细

数独解法

时间:2014-08-02 15:31:53      阅读:307      评论:0      收藏:0      [点我收藏+]
<pre name="code" class="cpp">
<pre name="code" class="cpp">//25...9.4.
//4.71.3..6
//8.34.759.
//3.8.7..69
//.1.3.24..
//5.49.6.83
//9.6.3.7.8
//.3.6.8.1.
//1.2.9.6.4


struct node
{
    node(int r,int c):row(r),col(c) {}
    friend ostream& operator <<(ostream& os,node& a)
    {
        cout<<a.row<<" "<<a.col<<endl;
        return os;
    }
    int row,col;
};

class Solution
{
    vector<node>holes;
    bool rowFlg[9][10];
    bool colFlg[9][10];
    bool rectFlg[3][3][10];
public:
    bool isValidSudoku(vector<vector<char> > &board)
    {
        memset(rowFlg,0,sizeof(rowFlg));
        memset(colFlg,0,sizeof(colFlg));
        memset(rectFlg,0,sizeof(rectFlg));
        holes.clear();
        for(int i=0; i<board.size(); i++)
        {
            for(int j=0; j<board[i].size(); j++)
            {
                if(board[i][j]=='.')holes.push_back(node(i,j));
                else
                {
                    rowFlg[i][board[i][j]-'0']=true;
                    colFlg[j][board[i][j]-'0']=true;
                    rectFlg[i/3][j/3][board[i][j]-'0']=true;
                }
            }
        }
        return display(board,holes.size()-1);
    }
    bool  display(vector<vector<char> > &board,int holeIndex)
    {
        if(holeIndex==-1)return true;
        for(int value=1; value<=9; value++)
        {
            if(checkCanDisplay(holes[holeIndex],value))
            {
                //放置
                node pos=holes[holeIndex];
                board[pos.row][pos.col]=value+'0';
                rowFlg[pos.row][value]=true;
                colFlg[pos.col][value]=true;
                rectFlg[pos.row/3][pos.col/3][value]=true;

                if(display(board,holeIndex-1))return true;

                rowFlg[pos.row][value]=false;
                colFlg[pos.col][value]=false;
                rectFlg[pos.row/3][pos.col/3][value]=false;
            }
        }
        return false;
    }
    bool checkCanDisplay(node pos,int value)
    {
       if(colFlg[pos.col][value]||rowFlg[pos.row][value]||rectFlg[pos.row/3][pos.col/3][value])
        return false;
        return true;
    }
};


数独解法,布布扣,bubuko.com

数独解法

原文:http://blog.csdn.net/ultimater/article/details/38348367

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!