深度优先搜索总结

来源:互联网 发布:b2b如何应用大数据 编辑:程序博客网 时间:2024/06/06 07:00

关于深搜,我也看了好多,和欧拉函数一样,一直没有理解其精髓,所以来总结·一下,先从四叉树的问题说起吧,当然,对于深搜,我没有深刻理解其精髓,以至于我就没有向深搜的那个方向去想,昨天看了别人的代码,感觉深搜的关键就是在于那个return,我就是这一点一直没有理解,return就是截止的意思,就是停止此次搜索,返回上一个层面,继续下一个阶层搜索,感觉就是这个样子,说起来简单,做起来难,先上一段代码,(四叉树深搜代码)

代码:

#include<stdio.h>#include<iostream>#include<algorithm>#include<string>#include<math.h>#include<string.h>#include<ctype.h>using namespace std;const int maxn=18;int map[maxn][maxn];string str[maxn];int n;bool check(int x,int y,int flag){    for(int i=0; i<flag; ++i)        for(int j=0; j<flag; ++j)            if(map[x+i][y+j]!=map[x][y])                return false;    return true;}void DFS(int x,int y,int flag,int deep)//搜索起始点坐标,坐标分割次数,递归深度{    string temp="1";    if(check(x,y,flag))    {        temp="0";        if(map[x][y]==0)            temp+="0";        else            temp+="1";        str[deep]+=temp;        return;    }    str[deep]+=temp;    DFS(x,y,flag>>1,deep+1);    DFS(x,y+(flag>>1),flag>>1,deep+1);    DFS(x+(flag>>1),y,flag>>1,deep+1);    DFS(x+(flag>>1),y+(flag>>1),flag>>1,deep+1);}int main(){    while(~scanf("%d",&n))    {        for(int i=0; i<n; ++i)            for(int j=0; j<n; ++j)                scanf("%d",&map[i][j]);        for(int i=0; i<maxn; ++i)            str[i]="";        DFS(0,0,n,0);        for(int i=0; i<=log2(n); ++i)            cout<<str[i];        cout<<endl;    }    return 0;}
感觉这个还是比较抽象的,这里还使用了string类,(这个知识点以后还是要总结的)

0 0
原创粉丝点击