数独算法

/*
 * File:   数独游戏算法,输入一个初始状态,如下图,0表示空
 103000509
 002109400
 000704000
 300502006
 060000050
 700803004
 000401000
 009205800
 804000107

 结果如图

143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127
 *
 * Author: chenjiang
 *
 * Created on 2010年5月5日, 下午12:29
 */

#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <stack>
#include <queue>

using namespace std;

int mapmap[10][10]; //保存整个
bool row[10][10], col[10][10], small_squre[10][10];

struct node {//定义一个点
    int x, y;
};

stack<node>S;//定义一个栈,用于保存空格子

int get_squre(int x, int y) {//获得(x,y)所在小方格的序号
    return x / 3 * 3 + y / 3;
}

bool Ok(int x, int y, int k) {//判断x行有没有数字k,y列有没有数字k,(x,y)所在的小方格有没有数字k
    if (!row[x][k] && !col[y][k] && !small_squre[get_squre(x, y)][k])return 1;
    else return 0;
}

bool dfs() {//深搜
    int i, k;
    if (!S.empty()) {
        node temp = S.top();
        S.pop();
        for (i = 1; i <= 9; i++) {
            if (Ok(temp.x, temp.y, i)) {
                row[temp.x][i] = 1;
                col[temp.y][i] = 1;
                small_squre[get_squre(temp.x, temp.y)][i] = 1;
                if (dfs()) {
                    mapmap[temp.x][temp.y] = i;
                    return 1;
                } else {
                    row[temp.x][i] = 0;
                    col[temp.y][i] = 0;
                    small_squre[get_squre(temp.x, temp.y)][i] = 0;
                }
            }
        }
        S.push(temp);
        return 0;
    }
    return 1;
}

/*
 *
 */
int main(int argc, char** argv) {

    int i, j, k;
    char ch[10];
    memset(row, 0, sizeof (row));
    memset(col, 0, sizeof (col));
    memset(small_squre, 0, sizeof (small_squre));
    while (!S.empty())S.pop();
    for (i = 0; i < 9; i++) {//0到8
        scanf("%s", ch);//每一行输入一个字符串,表示当前行的数字
        getchar();
        for (j = 0; j < 9; j++) {//
            k = ch[j] - '0';
            mapmap[i][j] = k;
            if (k) {
                row[i][mapmap[i][j]] = 1;
                col[j][mapmap[i][j]] = 1;
                small_squre[get_squre(i, j)][mapmap[i][j]] = 1;
            } else {
                node N;
                N.x = i;
                N.y = j;
                S.push(N);
            }
        }
    }

    dfs();//搜索

    /*打印结果*/
    for (i = 0; i < 9; i++) {
        for (j = 0; j < 9; j++) {
            cout << mapmap[i][j]<<" ";
        }
        cout << endl;
    }
    return (EXIT_SUCCESS);
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值