• 计蒜客 蓝桥模拟 F. 结果填空:数独


    代码:

    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    #include <iomanip>
    using namespace std;
    int n;
    int f[9][9];///记录每个位置的值  -1表示需要填
    int check(int x,int y,int k) {
        for(int i = 0;i < 9;i ++) {
            if(i != x && f[i][y] == k)return 0;
            if(i != y && f[x][i] == k)return 0;
        }
        int xx,yy;
        for(int i = 0;i < 3;i ++) {
            xx = x / 3 * 3 + i;
            for(int j = 0;j < 3;j ++) {
                yy = y / 3 * 3 + j;
                if(!(xx == x && yy == y) && f[xx][yy] == k)return 0;
            }
        }
        return 1;
    }
    void dfs(int x,int y) {//x代表行,y代表列,分别从0-8共9行(列)
        if(x == 9) {///x范围已过已经把表格填了一遍了  输出结果并返回
            for(int i = 0;i < 9;i ++) {
                for(int j = 0;j < 9;j ++) {
                    cout<<f[i][j]<<' ';
                }
                cout<<endl;
            }
            system("pause");
            return;
        }
        int xx = x,yy = y;
        f[x][y] = 1;///如果保持-1 下面循环不会进行 循环后会恢复为-1
        while(f[xx][yy] != -1) {
            if(xx >= 9)break;
            xx = xx + (yy + 1) / 9,yy = (yy + 1) % 9;///每循环一次yy+1,也就是从当前(x,y)的位置往右一行一行的遍历 找到下一个需要填的位置
        }
        f[x][y] = -1;
        for(int i = 1;i <= 9;i ++) {
            if(check(x,y,i)) {//当前填i可行的话 就dfs下一个需要填的位置(xx,yy)
                f[x][y] = i;
                dfs(xx,yy);
                f[x][y] = -1;//dfs终止表示这种策略不能dfs下去 位置值恢复为-1
            }
        }
    }
    int main() {
        memset(f,-1,sizeof(f));
        f[0][1] = 2;
        f[0][2] = 6;
        f[1][3] = 5;
        f[1][5] = 2;
        f[1][8] = 4;
        f[2][3] = 1;
        f[2][8] = 7;
        f[3][1] = 3;
        f[3][4] = 2;
        f[3][6] = 1;
        f[3][7] = 8;
        f[4][3] = 3;
        f[4][5] = 9;
        f[5][1] = 5;
        f[5][2] = 4;
        f[5][4] = 1;
        f[5][7] = 7;
        f[6][0] = 5;
        f[6][5] = 1;
        f[7][0] = 6;
        f[7][3] = 9;
        f[7][5] = 7;
        f[8][6] = 7;
        f[8][7] = 5;
        for(int i = 0;i < 9;i ++) {
            for(int j = 0;j < 9;j ++) {
                if(f[i][j] == -1)cout<<'*'<<' ';
                else cout<<f[i][j]<<' ';
            }
            cout<<endl;
        }
        getchar();
        dfs(0,0);
    }
  • 相关阅读:
    Mongoexport导出数据,Mongoimport导入数据,mongodump备份数据,mongorestore恢复恢复
    php7中使用mongodb的驱动
    windows(X64)+apche2.4+php7.2下安装mongodb
    windows(X64)下安装apche2.4+php7.2+mysql5.7
    Django2.0 path与Django1.x版本url正则匹配问题
    Django: ImportError: No module named 'corsheaders'
    linux开启端口
    MySQL 存储过程传参数实现where id in(1,2,3,...)示例
    ubuntu安装pip3
    在Ubuntu 16.04 安装python3.6 环境并设置为默认
  • 原文地址:https://www.cnblogs.com/8023spz/p/8660034.html
Copyright © 2020-2023  润新知