zoukankan      html  css  js  c++  java
  • 数独算法

    public boolean updateStdSudoKu()
        {
            Random random = new Random();
            for(int i=0;i<9;++i)
                for(int j=0;j<9;++j)
                    m_stdSudoKu[i][j] = 0;
    
            for(int i=0;i<9;++i)
                for(int j=0;j<9;++j)
                {
                     int left[] = new int[10];
                     for(int in=0;in<10;++in)
                         left[in] = in;
                    //
                    for(int col=0;col<9;++col)
                    {
                        if(col == j) continue;
                        if(m_stdSudoKu[i][col] !=0)
                            left[m_stdSudoKu[i][col]] = 0;
                    }
                    //
                    for(int row=0;row<9;++row)
                    {
                        if(row == i) continue;
                        if(m_stdSudoKu[row][j] != 0)
                            left[m_stdSudoKu[row][j]] = 0;
                    }
                    int blockStartI = (i / 3) * 3;
                    int blockStartJ = (j / 3) * 3;
                    for(int blockI = blockStartI;blockI < blockStartI+3;++blockI)
                        for(int blockJ = blockStartJ;blockJ < blockStartJ+3;++blockJ)
                        {
                            if(i==blockI && j==blockJ) continue;
                            if(m_stdSudoKu[blockI][blockJ] != 0)
                                left[m_stdSudoKu[blockI][blockJ]] = 0;
                        }
    
                    int resLeft[] = new int[9];
                    int cnt = 0;
                    for(int resI = 0;resI < 10;++resI)
                        if(left[resI] != 0)
                        {
                            resLeft[cnt++] = left[resI];
                        }
                    if(cnt == 0)
                    {
                        return false;
                    }
                    int randomI = random.nextInt(cnt);
                    m_stdSudoKu[i][j] = resLeft[randomI];
                }
                return true;
        }

    其中m_stdSudoKu[9][9]是9*9的数组,用于保存完整的数独。这个函数由于一次可能无法得到数独,所以调用的时候需要循环调用,知道返回true。

    该算法原理就是每次得到某个空格数字就要进行3重限制的校对,排除横,竖,3*3宫格已经出现过的数字。

  • 相关阅读:
    E
    C
    航空母舰-03
    航空母舰-02
    航空母舰-01
    新概念4-30
    html
    翁凯-编程学习方法
    机器学习Ng-02
    民法-钟秀勇-导学
  • 原文地址:https://www.cnblogs.com/jlyg/p/8184211.html
Copyright © 2011-2022 走看看