DFS和BFS(含常用模板)

DFS(深度优先搜索)

其实就是暴力把所有的路径都搜索出来,它运用了回溯,保存这次的位置,深入搜索,都搜索完了便回溯回来,搜下一个位置,直到把所有最深位置都搜一遍,要注意的一点是,搜索的时候有记录走过的位置,标记完后可能要改回来;

回溯法是一种搜索法,按条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择达不到目标,就退回一步重新选择,这种走不通就退回再走的方法为回溯法;
在这里插入图片描述

例如这张图,从1开始到2,之后到5,5不能再走了,退回2,到6,退回2退回1,到3,一直进行;

DFS模板:

void dfs(根据需要传递相应的参数)
{
    if(满足条件)退出当前函数
    if(剪枝)剪掉该分支
    
    如果以上都不满足就枚举情况进行递归
    for(......)
    {
        状态标记
        dfs(...)
        状态恢复
    }
}

例题:HDU-1016
Problem Description
A ring is compose of n circles as shown in diagram. Put natural number 1, 2, …, n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.

Note: the number of first circle should always be 1.

Input
n (0 < n < 20).

Output
The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.

You are to write a program that completes above process.

Print a blank line after each case.

Sample Input
6
8

Sample Output
Case 1:
1 4 3 2 5 6
1 6 5 2 3 4

Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2

Source
Asia 1996, Shanghai (Mainland China)

Recommend
JGShining
题意:
将自然数1,2,…,n分别放入一个圆中,相邻两个圆中的数之和应为素数。第一个圆的数目应始终为1。
思路:
先打印出一张素数表,不用存储素数的,是素数的标记为1,不是标记为0.然后再进行深度优先搜索,出口相邻的二个数相加为素数。

#include<stdio.h>
#include<string.h>
void dfs(int cur);
int prime(int x);

int n,a[20],b[41],c[20];

int main()
{
     int i;
     for(i=2;i<=40;i++)
        b[i]=prime(i);//打表
     int k=1;  
     while(scanf("%d",&n)!=EOF)
     {
        a[0]=1;
        printf("Case %d:\n",k++);
        if(n%2==0)
        {
        	dfs(1);开始深搜
		}
       printf("\n");
     }  
	 return 0;    
}

int prime(int x)
{
    int i;
    for(i=2;i*i<=x;i++)
       if(x%i==0)
       {
         return 0;
         break;
        }
    return 1;
} 
     
void dfs(int cur)
{
	int i;
    if(cur==n&&b[a[0]+a[n-1]])
    {
        for(i=0;i<n-1;i++)
           printf("%d ",a[i]);
        printf("%d\n",a[n-1]);
    }
    else
      for(i=2;i<=n;i++)
         if(!c[i]&&b[i+a[cur-1]])
         {
                a[cur]=i;
                c[i]=1;
                dfs(cur+1);
                c[i]=0;
        }
 
}  

BFS(广度优先搜索)

从某点开始,走四面可以走的路,然后在从这些路,在找可以走的路,直到最先找到符合条件的,这个运用需要用到队列(queue),需要稍微掌握这个才能用bfs。
在这里插入图片描述

还是这张图,从1开始搜,有2,3,4几个点,存起来,从2开始有5,6,存起来,搜3,有7,8,存起来,搜4,没有了;现在开始搜刚刚存的点,从5开始,没有,然后搜6.。。一直进行,直到找到;

BFS模板:

void  BFS()
{
    队列初始化;
    初始结点入队;
    while (队列非空)
    {  
          队头元素出队,赋给current;
          while  (current 还可以扩展)
          {
              由结点current扩展出新结点new;
              if  (new 重复于已有的结点状态) continue;
              new结点入队;
              if  (new结点是目标状态)
              {
                    置flag= true;    break; 
               }
          }
      }
}

广度优先搜索算法的搜索步骤一般是:

  (1)从队列头取出一个结点,检查它按照扩展规则是否能够扩展,如果能则产生一个新结点。

   (2)检查新生成的结点,看它是否已在队列中存在,如果新结点已经在队列中出现过,就放弃这个结点,然后回到第(1)步。否则,如果新结点未曾在队列中出现过,则将它加入到队列尾。

  (3)检查新结点是否目标结点。如果新结点是目标结点,则搜索成功,程序结束;若新结点不是目标结点,则回到第(1)步,再从队列头取出结点进行扩展。

  最终可能产生两种结果:找到目标结点,或扩展完所有结点而没有找到目标结点。

例题:HDU-2102
A计划
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 42586 Accepted Submission(s): 10570

Problem Description
可怜的公主在一次次被魔王掳走一次次被骑士们救回来之后,而今,不幸的她再一次面临生命的考验。魔王已经发出消息说将在T时刻吃掉公主,因为他听信谣言说吃公主的肉也能长生不老。年迈的国王正是心急如焚,告招天下勇士来拯救公主。不过公主早已习以为常,她深信智勇的骑士LJ肯定能将她救出。
现据密探所报,公主被关在一个两层的迷宫里,迷宫的入口是S(0,0,0),公主的位置用P表示,时空传输机用#表示,墙用*表示,平地用.表示。骑士们一进入时空传输机就会被转到另一层的相对位置,但如果被转到的位置是墙的话,那骑士们就会被撞死。骑士们在一层中只能前后左右移动,每移动一格花1时刻。层间的移动只能通过时空传输机,且不需要任何时间。

Input
输入的第一行C表示共有C个测试数据,每个测试数据的前一行有三个整数N,M,T。 N,M迷宫的大小NM(1 <= N,M <=10)。T如上所意。接下去的前NM表示迷宫的第一层的布置情况,后N*M表示迷宫第二层的布置情况。

Output
如果骑士们能够在T时刻能找到公主就输出“YES”,否则输出“NO”。

Sample Input
1
5 5 14
S*#*.
.#…

****.
…#.

.P
#.

**
.
*.#…

Sample Output
YES

#include <stdio.h>
#include <cstring>
#include <queue>
using namespace std;

struct node
{
    int x,y,floor;
    int step;
};

int t,n,m,lim;
int s[3],e[3];
int to[4][2] = {1,0,0,1,-1,0,0,-1};
char map[2][15][15];
int use[2][15][15];

int check(int floor,int x,int y)
{
    if(x<0 || y<0 || x>=n || y>=m)
        return 1;
    if(map[floor][x][y]=='*')
        return 1;
    return 0;
}

void BFS()
{
    memset(use,0,sizeof(use));
    node a,next;
    queue<node> Q;
    int i,j,k;
    a.floor = s[0];
    a.x = s[1];
    a.y = s[2];
    a.step = 0;
    use[s[0]][s[1]][s[2]] = 1;
    Q.push(a);
    while(!Q.empty())
    {
        a = Q.front();
        Q.pop();
        if(a.floor == e[0] && a.x == e[1] && a.y == e[2])
        {
            printf("YES\n");
            return ;
        }
        if(a.step>=lim)
            break;
        for(i = 0; i<4; i++)
        {
            next = a;
            next.x+=to[i][0];
            next.y+=to[i][1];
            next.step++;
            if(check(next.floor,next.x,next.y))
                continue;
            if(use[next.floor][next.x][next.y])
                continue;
            use[next.floor][next.x][next.y] = 1;
            if(map[next.floor][next.x][next.y] == '#')
            {
                next.floor=!next.floor;
                if(check(next.floor,next.x,next.y))
                    continue;
                if(use[next.floor][next.x][next.y])
                    continue;
                if(map[next.floor][next.x][next.y] == '*' || map[next.floor][next.x][next.y] == '#')
                    continue;
                use[next.floor][next.x][next.y] = 1;
            }
            if(next.floor == e[0] && next.x == e[1] && next.y == e[2])
            {
                printf("YES\n");
                return ;
            }
            Q.push(next);
        }
    }
    printf("NO\n");
}

int main()
{
    int i,j,k;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d%d",&n,&m,&lim);
        for(int k=0;k<2;k++)
        {
            for(i=0;i<n;i++)
            {
                scanf("%s",map[k][i]);
                for(j = 0; j<m; j++)
                {
                    if(map[k][i][j] == 'S')
                    {
                        s[0] = k,s[1] = i,s[2] = j;
                    }
                    else if(map[k][i][j] == 'P')
                    {
                        e[0] = k,e[1] = i,e[2] = j;
                    }
                }
            }
        }
        BFS();
    }

    return 0;
}
  • 1
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沐雨风栉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值