zoukankan      html  css  js  c++  java
  • 数独问题

    #include <bits/stdc++.h>
    using namespace std;
    const int maxn = 20;
    int ans[maxn][maxn]={
    {8,0,4,0,9,0,3,2,0},
    {0,0,1,0,0,0,8,0,0},
    {6,0,0,0,0,8,0,9,7},
    {5,0,0,0,3,0,2,0,0},
    {7,0,0,0,0,0,0,0,0},
    {0,0,9,0,0,5,0,4,0},
    {0,0,7,8,1,0,9,0,0},
    {1,0,0,0,0,4,0,0,0},
    {4,0,3,0,6,9,0,7,0},
    };
    bool hashcol[maxn][maxn];
    bool hashrow[maxn][maxn];
    bool hashblo[maxn][maxn];
    void upda(int x,int y,int z)
    {
         hashcol[x][ans[x][y]]=z;
         hashrow[y][ans[x][y]]=z;
         hashblo[x/3*3+y/3][ans[x][y]]=z;
    }
    bool dfs(int x,int y)
    {
        while(ans[x][y])
        {
            if(x==8&&y==8)return true;
            if(y==8)y=0,x++;
            else y++;
        }
        for(int k=1;k<=9;k++)
        {
            if(!hashcol[x][k]&&!hashrow[y][k]&&!hashblo[x/3*3+y/3][k])
            {
                ans[x][y]=k;
                upda(x,y,1);
                if(dfs(x,y))return true;
                upda(x,y,0);
                ans[x][y]=0;
            }
        }
        return false;
    }
    int main()
    {
        for(int x=0;x<9;x++)
        for(int y=0;y<9;y++)
            upda(x,y,1);
        if(dfs(0,0))
        {
            for(int x=0;x<9;x++)
            {
                for(int y=0;y<9;y++)
                  cout<<ans[x][y]<<" ";
                cout<<endl;
            }
        }
        else
        {
            cout<<"no answer!"<<endl;
        }
        return 0;
    }
    

      

  • 相关阅读:
    tp5.1 多级控制器
    JS中三个点(...)是什么鬼?
    vue reqwest与fetch的使用
    new Vue({ render: h => h(App), }).$mount('#app')到底什么意思
    ant design vue 表格和国际化的使用
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA日报
  • 原文地址:https://www.cnblogs.com/carcar/p/10484449.html
Copyright © 2011-2022 走看看