数独 问题求解

问题描述:
对于一个9*9的一组方格,每一行,每一列,3 *3的小方格区域内填入1-9,每个数字只出现一次。

代码编写:
此题与八皇后问题解法非常相同。

#include <iostream>
#include <vector>
using namespace std;

#define N 9

static int count = 0;

//定义一个数独数组,其中0表示需要填入 
int shudu[N][N] = {7,3,0,2,1,8,5,0,4,
                   2,1,0,0,0,9,0,0,3,
                   5,9,0,0,7,0,2,8,1,
                   3,4,1,8,6,0,9,2,7,
                   0,6,0,0,9,0,0,1,0,
                   9,5,2,0,4,1,8,3,6,
                   4,7,3,0,8,0,0,5,2,
                   6,0,0,1,0,0,0,4,9,
                   1,0,9,5,3,4,0,6,8};


//int shudu[N][N] = {0};

struct pos{
    int row;
    int col;
};

vector<pos> vt;

//初始化,扫描数组中哪些位置需要填空 
void init(){
    for(int i = 0; i < N; i++){
        for(int j = 0; j < N; j++){
            if(shudu[i][j] == 0){
                pos p;
                p.row = i;
                p.col = j;
                vt.push_back(p);
            }
        }
    }
}

//打印 
void print(int shudu[N][N]){
    for(int i = 0; i < N; i++){
        for(int j = 0; j < N; j++){
            cout<<shudu[i][j]<<", ";
        }
        cout<<endl;
    }
    cout<<endl;
}

//检测填入的数是否合法 
bool check(int row, int col)
{
    bool ret = true;

    // 列方向检测
    for (int i = 0; i < 9; i++){
        if(shudu[i][col] == shudu[row][col] && i != row){
            ret = false;
            return ret;
        }
    }

    // 行方向检测
    for (int j = 0; j < 9; j++){
        if(shudu[row][j] == shudu[row][col] && j != col){
            ret = false;
            return ret;
        }
    }

    // 区域检测
    int block_row = row / 3 * 3;
    int block_col = col / 3 * 3;
    for (int i = block_row; i < block_row + 3; i++)
    {
        for (int j = block_col; j < block_col + 3; j++)
        {
            if(shudu[i][j] == shudu[row][col] && i != row && j != col){
                ret = false;
                return ret;
            }
        }
    }
    return ret;
}

void solve(int i){
    if(i >= vt.size()){
        count++;
        cout<<"第 "<<count<<" 种解法:"<<endl;
        print(shudu);
//      cin.get(); 
    }else{
        int row = vt[i].row;
        int col = vt[i].col;
        for (int a = 1; a <= 9; a++){
            shudu[row][col] = a;
            if(check(row, col)){
                solve(i+1);
            }
            shudu[row][col] = 0;
        }   
    }
}

int main(){

    cout<<"数独:"<<endl;
    print(shudu);

    init(); 
    solve(0);

    return 0;
}

运行结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值