深搜和广搜简单对比

来源:互联网 发布:网络诈骗无人管 编辑:程序博客网 时间:2024/04/30 06:43

近来在学习搜索,写个博客记录一下,也是本人在CSDN的第一篇博客,内容上有不对的地方希望大家指出,一同进步!
深搜和广搜在实现上分别用的是栈(栈和函数递归本质是一样)和队列。广搜一般对于寻找最优解的情况有比较好的时间控制,但是比较消耗内存。相反深搜却比较省内存但在时间上会有所消耗!所以在选择深搜还是广搜时看时间和内存的限制。当然还有更优化的算法!各种形象
化的动态解释大牛博客上都有,下面贴一个入门级的搜索深搜和广搜代码。(百炼3752深搜,广搜)。
总时间限制:
1000ms
内存限制:
65536kB
描述
一个迷宫由R行C列格子组成,有的格子里有障碍物,不能走;有的格子是空地,可以走。
给定一个迷宫,求从左上角走到右下角最少需要走多少步(数据保证一定能走到)。只能在水平方向或垂直方向走,不能斜着走。
输入
第一行是两个整数,R和C,代表迷宫的长和宽。( 1<= R,C <= 40)
接下来是R行,每行C个字符,代表整个迷宫。
空地格子用’.’表示,有障碍物的格子用’#’表示。
迷宫左上角和右下角都是’.’。
输出
输出从左上角走到右下角至少要经过多少步(即至少要经过多少个空地格子)。计算步数要包括起点和终点。
样例输入

    5 5    ..###    #....    #.#.#    #.#.#    #.#..样例输出    9深搜代码:
#include<iostream>#include<cstring>using namespace std;int R,C;char maps[40][40];int dp[40][40];int dir[2][4]={{1,0,0,-1},{0,1,-1,0}};int ans=1<<30;void DFS(int x,int y,int step){      if(x>=R || y>=C || x<0 ||y<0) return ;      if(x==R-1&&y==C-1) {        if(step<ans) ans=step;        return ;      }      if(maps[x][y]=='#') return;      for(int i=0;i<4;i++){            if(x+dir[0][i] >=R || y+dir[1][i] >=C || x+dir[0][i] <0 || y+dir[1][i] < 0 ) continue;            if(maps[x+dir[0][i]][y+dir[1][i]]=='.' && !dp[x+dir[0][i]][y+dir[1][i]]){                 dp[x+dir[0][i]][y+dir[1][i]]=1;                 DFS(x+dir[0][i],y+dir[1][i],step+1);                 dp[x+dir[0][i]][y+dir[1][i]]=0;            }      }}int main(){    cin>>R>>C;    char c;    for(int i=0;i<R;i++)    for(int j=0;j<C;j++){        cin>>c;        maps[i][j]=c;        dp[i][j]=0;    }    dp[0][0]=1;    DFS(0,0,1);    cout<<ans<<endl; return 0; }

广搜代码:

#include<iostream>#include<algorithm>#include<cstring>#include<queue>using namespace std;int R,C;char maps[40][40];int dp[40][40];int dir[2][4]={{1,0,0,-1},{0,1,-1,0}};int ans=1<<30;struct node{    int x;    int y;    int step;    node(int xx,int yy,int tt):x(xx),y(yy),step(tt){}};int  bfs(){     queue<node> que;     que.push(node(0,0,1));     while(!que.empty()){        node temp = que.front();        que.pop();        for(int i=0;i<4;i++){     //上下左右四方向            int tx=temp.x+dir[0][i];            int ty=temp.y+dir[1][i];            int tt=temp.step;            if(dp[tx][ty]) continue;            if(tx<0 || tx>=R  || ty<0  || ty>=C ) continue;            if(maps[tx][ty]=='#') continue;            if(tx==R-1&&ty==C-1) return tt+1;            dp[tx][ty]=1;            que.push(node(tx,ty,tt+1));        }    }}int main(){    cin>>R>>C;    for(int i=0;i<R;i++)    for(int j=0;j<C;j++){        cin>>maps[i][j];        dp[i][j]=0;    }    int ans=bfs();    cout<<ans<<endl;    return 0;}
0 1
原创粉丝点击