zoukankan      html  css  js  c++  java
  • 程序解数独

    #include <bits/stdc++.h>
    using namespace std;
    /* run this program using the console pauser or add your own getch, system("pause") or input loop */
    
    
    bool line[9][9];
    bool column[9][9];
    bool block[3][3][9];
    bool valid;
    vector<pair<int, int>> spaces;
    
    void dfs(vector<vector<char>>& board, int pos) {
        if (pos == spaces.size()) {
            valid = true;
            return;
        }
    
        auto [i, j] = spaces[pos];
        for (int digit = 0; digit < 9 && !valid; ++digit) {
            if (!line[i][digit] && !column[j][digit] && !block[i / 3][j / 3][digit]) {
                line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = true;
                board[i][j] = digit + '0' + 1;
                dfs(board, pos + 1);
                line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = false;
            }
        }
    }
    
    void solveSudoku(vector<vector<char>>& board) {
        memset(line, false, sizeof(line));
        memset(column, false, sizeof(column));
        memset(block, false, sizeof(block));
        valid = false;
    
        for (int i = 0; i < 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                if (board[i][j] == '.') {
                    spaces.emplace_back(i, j);
                }
                else {
                    int digit = board[i][j] - '0' - 1;
                    line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = true;
                }
            }
        }
    
        dfs(board, 0);
    }
    
    int main(int argc, char** argv) {
        vector<vector<char>> board(9);
        for(int i =0;i<9;i++)
            board.resize(9);
        cout<<"输入"<<endl;
        for(int i = 0;i<9;i++)
            for(int j = 0; j<9;j++)
                cin>>board[i][j];
        for(char row : board)
            for(int i =0;i<9;i++)
                cout<<row[i]<<"	";
            cout<<'
    ';
        return 0;
    }
  • 相关阅读:
    .net core 灵活读取配置文件
    SUSE12SP3-Mysql5.7安装
    SUSE12Sp3-MongoDB安装
    SUSE12Sp3-Supervisor 守护.net core进程
    SUSE12Sp3-Nginx安装
    SUSE12Sp3-.NET Core 2.2.1 runtime安装
    搭建consul 集群
    SUSE12Sp3安装配置.net core 生产环境(1)-IP,DNS,网关,SSH,GIT
    使用Consul 实现 MagicOnion(GRpc) 服务注册和发现
    使用MagicOnion实现gRPC
  • 原文地址:https://www.cnblogs.com/ranzhong/p/14342068.html
Copyright © 2011-2022 走看看