数独 DFS(C++)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41033913/article/details/79997783

深搜:(赋自己一点点解释,希望有帮助)

#include<bits/stdc++.h>
        //万能头文件,但是有些系统不能使用
using namespace std;
int mp[9][9];//用来存原始数据,需要设为全局变量
bool Isok(int n)
{
    int row=n/9;//找到所在行
    int col=n%9;//列

    for(int i=0;i<9;i++){
        if(mp[row][i]==mp[row][col]&&i!=col)
            return false;
    }
    for(int i=0;i<9;i++){
         if(mp[i][col]==mp[row][col]&&i!=row)
            return false;
    }
    //判断行和列是否有重复
    int temprow=row/3*3;
    int tempcol=col/3*3;
    for(int i=temprow;i<temprow+3;i++){
        for(int j=tempcol;j<tempcol+3;j++){
            if(mp[i][j]==mp[row][col]&&i!=row&&j!=col)
                return false;
        }
    }
    //判断小格里面是否重复
    return true;
}

void DFS(int n)
{
    if(n==81){//深搜完毕,输出
        cout<<"存在:"<<endl;
        for(int i=0;i<9;i++){
            for(int j=0;j<9;j++){
                cout<<mp[i][j]<<" ";
            }
            cout<<endl;
        }
        return ;
    }
    int row=n/9;
    int col=n%9;
    if(mp[row][col]==0){
        for(int i=1;i<=9;i++){
            mp[row][col]=i;//赋值
            if(Isok(n))//判断赋值是否符合要求
                DFS(n+1);//如果符合便深搜下一个
        }
        mp[row][col]=0;//不符合,需进行剪枝要重新赋0
                      //这样才能在重新回溯到的时候没有破坏原始数据
    }
    else DFS(n+1);
}
int main()
{
    for(int i=0;i<9;i++){
        for(int j=0;j<9;j++)
            cin>>mp[i][j];
    }
    DFS(0);
    return 0;
}

测试数据:

9 0 0 0 0 4 0 0 1
0 1 6 0 0 8 0 7 0
0 0 0 0 0 0 0 8 0
7 4 0 3 0 5 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 7 0 2 0 3 8
0 5 0 0 0 0 0 0 0
0 7 0 2 0 0 3 5 0
1 0 0 6 0 0 0 0 9

运行结果:

存在:
9 8 7 5 3 4 2 6 1
3 1 6 9 2 8 4 7 5
4 2 5 1 7 6 9 8 3
7 4 8 3 6 5 1 9 2
2 6 3 8 1 9 5 4 7
5 9 1 7 4 2 6 3 8
8 5 2 4 9 3 7 1 6
6 7 9 2 8 1 3 5 4
1 3 4 6 5 7 8 2 9

自己写的时候判断赋值是否符合要求的时候多加了一个封号,找了一个多小时大哭。。。

希望看到的人注意!
 

猜你喜欢

转载自blog.csdn.net/qq_41033913/article/details/79997783
今日推荐