【编程受害者实录*搜索】

那么问题来了,我连bfs和dfs还不怎么弄得明白,为什么要试图去写搜索的题目呢?
答:生活所迫。
本篇笔记我估摸着应该都是别人的代码我修改后的版本。
强力安利https://blog.csdn.net/u011437229/article/details/53188837#commentBox
https://blog.csdn.net/raphealguo/article/details/7523411

笔记:
1.BFS是用来搜索最短径路的解是比较合适的,比如求最少步数的解,最少交换次数的解,因为BFS搜索过程中遇到的解一定是离根最近的,所以遇到一个解,一定就是最优解,此时搜索算法可以终止。这个时候不适宜使用DFS,因为DFS搜索到的解不一定是离根最近的,只有全局搜索完毕,才能从所有解中找出离根的最近的解。(当然这个DFS的不足,可以使用迭代加深搜索ID-DFS去弥补【不懂】)

2.空间优劣上,DFS是有优势的,DFS不需要保存搜索过程中的状态,而BFS在搜索过程中需要保存搜索过的状态,而且一般情况需要一个队列来记录

3.DFS适合搜索全部的解,因为要搜索全部的解,那么BFS搜索过程中,遇到离根最近的解,并没有什么用,也必须遍历完整棵搜索树,DFS搜索也会搜索全部,但是相比DFS不用记录过多信息,所以搜素全部解的问题,DFS显然更加合适。

4.DFS最大特色就在于其递归特性

一个普通dfs模板

5.bfs模板
一个普通bfs模板

手动目录:棋盘问题
Dungeon Master
迷宫问题
Oil Deposits
Shuffle’m Up

#棋盘问题

在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子的所有可行的摆放方案C。
Input
输入含有多组测试数据。
每组数据的第一行是两个正整数,n k,用一个空格隔开,表示了将在一个n*n的矩阵内描述棋盘,以及摆放棋子的数目。 n <= 8 , k <= n
当为-1 -1时表示输入结束。
随后的n行描述了棋盘的形状:每行有n个字符,其中 # 表示棋盘区域, . 表示空白区域(数据保证不出现多余的空白行或者空白列)。
Output
对于每一组数据,给出一行输出,输出摆放的方案数目C (数据保证C<2^31)。
Sample Input
2 1
#.
.#
4 4
…#
…#.
.#…
#…
-1 -1
Sample Output
2
1

思路:求所有方案数一般dfs,每次从i行开始数,扫描完则从i+1行开始,反正一行只能放一个【语死早,还是看代码吧】

#include <stdio.h>
int b[12]= {0}; //b数组表示此列未被放棋子
int sum;//计数
int n,k,t;
char s[12][12];
void search2(int i)
{
    if(t==k)//到达次数
    {
        sum++;
        return ;//返回
    }
    if(i>n)//超出边界返回
        return ;
    for(int j=0; j<n; j++)
    {
        if(s[i][j]=='#'&&!b[j])//此处为棋盘并且此列不存在别的棋子
        {
            b[j]=1;
            t++;//放入一个棋子
            search2(i+1);
            b[j]=0;//回溯
            t--;


        }
    }
    search2(i+1);//此处返回


}
int main()
{
    while(scanf("%d %d",&n,&k)!=EOF)
    {
        if(n==-1&&k==-1)
            break;
        t=0;
        sum=0;
        getchar();
        for(int i=1; i<=n; i++)
        {
            gets(s[i]);

        }
        search2(1);
        printf("%d\n",sum);
    }
    return 0;

}

#Dungeon Master

You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move diagonally and the maze is surrounded by solid rock on all sides.

Is an escape possible? If yes, how long will it take? Input The input consists of a number of dungeons. Each dungeon description starts with a line containing three integers L, R and C (all limited to 30 in size). L is the number of levels making up the dungeon. R and C are the number of rows and columns making up the plan of each level. Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a ‘#’ and empty cells are represented by a ‘.’. Your starting position is indicated by ‘S’ and the exit by the letter ‘E’. There’s a single blank line after each level.
Input is terminated by three zeroes for L, R and C. Output Each maze generates one line of output. If it is possible to reach the exit, print a line of the form Escaped in x minute(s).

where x is replaced by the shortest time it takes to escape. If it is not possible to escape, print the line Trapped!
Sample Input
3 4 5
S…
.###.
.##…
###.#

##.##
##…

#.###
####E

1 3 3
S##
#E#

0 0 0
Sample Output
Escaped in 11 minute(s).
Trapped!

思路:走迷宫问题,只是从四个方向变成八个方向,问最短时间则bfs,结构体+队列来写,到了目的地输出时间。

#include <stdio.h>
#include <queue>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;

char map[35][35][35];
int l,r,c;//L层数,r为row,c为列数
int vis[35][35][35];//表示已经路过;
int sx,sy,sz,ex,ey,ez;
int to[6][3]= {{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};
/*                东     西      南        北      上       下*/

struct node
{
    int x,y,z,step;

};

int check(int x,int y,int z)
{
    if(x<0||y<0||z<0||x>=l||y>=r||z>=c)
        return 1;//超出范围
    else if(map[x][y][z] == '#')
        return 1;//岩石不能走
    else if(vis[x][y][z])
        return 1;//已经走过
        
    return 0;


}

int bfs()
{
    int i;
    node a,next;
    queue<node> Q;
    a.x=sx,a.y=sy,a.z=sz;
    a.step=0;
    vis[sx][sy][sz]=1;//出发点
    Q.push(a);//将包含出发位置信息的结构体压入队列
    while(!Q.empty())
    {
        a=Q.front();//a等于队列第一个
        Q.pop();//弹出第一个队列
        if(a.x==ex&&a.y==ey&&a.z==ez)
        {
            return a.step;//达到出口,则返回步数
        }
        for(int i=0; i<6; i++)
        {
            next=a;
            next.x = a.x+to[i][0];
            next.y = a.y+to[i][1];
            next.z = a.z+to[i][2];
            if(check(next.x,next.y,next.z))
                continue;//不满足检查则换个方向
                
            vis[next.x][next.y][next.z] = 1;//已经路过
            next.step = a.step+1;//步数+1
            Q.push(next);//压入队列
        }
    }
    return 0;


}
int main()
{
      int i,j,k;
    while(scanf("%d %d %d",&l,&r,&c),l+r+c)
    {
        for(i=0; i<l; i++)
        {
            for(j=0; j<r; j++)
            {
                scanf("%s",map[i][j]);
                for(k=0; k<c; k++)
                {
                    if(map[i][j][k]=='S')
                    {
                        sx = i,sy = j,sz = k;
                    }
                    else if(map[i][j][k]=='E')
                    {
                        ex = i,ey = j,ez = k;
                    }


                }
            }

        }
        memset(vis,0,sizeof(vis));
        int sum;
        sum=bfs();
        if(sum)
            printf("Escaped in %d minute(s).\n",sum);
        else
            printf("Trapped!\n");

    }
    return 0;
}

#迷宫问题

定义一个二维数组:

int maze[5][5] = {

0, 1, 0, 0, 0,

0, 1, 0, 1, 0,

0, 0, 0, 0, 0,

0, 1, 1, 1, 0,

0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

思路:搜索最短的路径,记录并输出,重点是要保存路径。

#include <cstdio>
#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
struct node
{
    int x,y;
    int prex,prey;//记录去过的坐标
} s[5][5];
int sum;
int maze[5][5];
int sx,sy;//开始
int gx,gy;//终点
int vis[6][6];//不仅是去过还是步数
int dx[4] = {1,0,-1,0},dy[4] = {0,1,0,-1};//方向
void print(int x,int y)//递归打印
{
    if(x==0&&y==0)
    {
        printf("(0, 0)\n");//因为这个点没有前面的点
        return;

    }
    int prex=s[x][y].prex;
    int prey=s[x][y].prey;
    print(prex,prey);//递归
    printf("(%d, %d)\n",s[x][y].x,s[x][y].y);
}
void bfs(int x,int y)
{
      queue<node>Q;
      memset(vis,0,sizeof(vis));
      Q.push(s[0][0]);
      while(!Q.empty())
      {
            node exa;
            exa=Q.front();
            Q.pop();
            if(exa.x==gx&&exa.y==gy)return;
            for(int i=0;i<4;i++)//四个方向
            {
                  int nx=exa.x+dx[i];
                  int ny=exa.y+dy[i];
                  if(nx>=0&&ny>=0&&nx<5&&ny<5&&maze[nx][ny]!=1&&!vis[nx][ny])
                  {
                        maze[nx][ny]=1;
                        s[nx][ny].x=nx;
                        s[nx][ny].y=ny;
                        s[nx][ny].prex=exa.x;
                        s[nx][ny].prey=exa.y;
                        Q.push(s[nx][ny]);
                        vis[nx][ny]=vis[exa.x][exa.y]+1;
                  }
            }

      }
}
int main()
{
    sx=0,sy=0;
    gx=4,gy=4;
    for(int i=0; i<=4; i++)
    {
        for(int j=0; j<=4; j++)
        {
            scanf("%d",&maze[i][j]);
        }
    }
    bfs(0,0);
    print(4,4);
    return 0;
}

#Oil Deposits

The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.
Input
The input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either *', representing the absence of oil, or@’, representing an oil pocket.
Output
For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.
Sample Input
1 1
*
3 5
@@*
@
@@*
1 8
@@***@
5 5
****@
@@@
@**@
@@@
@
@@**@
0 0
Sample Output
0
1
2
2

思路:联通块问题,先找到一个油田,sum+1,然后开始往四周搜,是油田则标记,不是油田就返回。返回完后,继续找下一块没被标记的油田,sum+1,又开始联通。

#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
int sum;
char x[101][101];
int m,n;
int check(int i,int j)
{
    if(i<0||j<0||i>=m||j>=n)
        return 1;
    if(x[i][j]!='@')
        return 1;
    return 0;

}
void dfs(int i,int j)
{
    if(check(i,j))
        return;
    else
    {
        x[i][j]='*';
        dfs(i-1, j-1);
        dfs(i-1, j);
        dfs(i-1, j+1);
        dfs(i, j-1);
        dfs(i, j+1);
        dfs(i+1, j-1);
        dfs(i+1, j);
        dfs(i+1, j+1);
    }


}
int main()
{
    while(scanf("%d%d",&m,&n)!=EOF)
    {
        if(m==0||n==0)
            break;
        for(int i=0; i<m; i++)//输入
        {
            for(int j=0; j<n; j++)
            {
                cin>>x[i][j];//小心scanf会出错
            }

        }
        sum=0;
        for(int i=0; i<m; i++)
        {
            for(int j=0; j<n; j++)
            {
                if(x[i][j]=='@')
                {
                    dfs(i,j);
                    sum++;
                }
            }
        }
        printf("%d\n",sum);


    }
    return 0;
}

#Shuffle’m Up

A common pastime for poker players at a poker table is to shuffle stacks of chips. Shuffling chips is performed by starting with two stacks of poker chips, S1 and S2, each stack containing C chips. Each stack may contain chips of several different colors.

The actual shuffle operation is performed by interleaving a chip from S1 with a chip from S2 as shown below for C = 5:

The single resultant stack, S12, contains 2 * C chips. The bottommost chip of S12 is the bottommost chip from S2. On top of that chip, is the bottommost chip from S1. The interleaving process continues taking the 2nd chip from the bottom of S2 and placing that on S12, followed by the 2nd chip from the bottom of S1 and so on until the topmost chip from S1 is placed on top of S12.

After the shuffle operation, S12 is split into 2 new stacks by taking the bottommost C chips from S12 to form a new S1 and the topmost C chips from S12 to form a new S2. The shuffle operation may then be repeated to form a new S12.

For this problem, you will write a program to determine if a particular resultant stack S12 can be formed by shuffling two stacks some number of times.

Input
The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.

Each dataset consists of four lines of input. The first line of a dataset specifies an integer C, (1 ≤ C ≤ 100) which is the number of chips in each initial stack (S1 and S2). The second line of each dataset specifies the colors of each of the C chips in stack S1, starting with the bottommost chip. The third line of each dataset specifies the colors of each of the C chips in stack S2 starting with the bottommost chip. Colors are expressed as a single uppercase letter (A through H). There are no blanks or separators between the chip colors. The fourth line of each dataset contains 2 * C uppercase letters (A through H), representing the colors of the desired result of the shuffling of S1 and S2 zero or more times. The bottommost chip’s color is specified first.

Output
Output for each dataset consists of a single line that displays the dataset number (1 though N), a space, and an integer value which is the minimum number of shuffle operations required to get the desired resultant stack. If the desired result can not be reached using the input for the dataset, display the value negative 1 (−1) for the number of shuffle operations.

Sample Input
2
4
AHAH
HAHA
HHAAAAHH
3
CDE
CDE
EEDDCC
Sample Output
1 2
2 -1
在这里插入图片描述

思路:真没想到用搜索…求最少的次数当然还是用dfs,要小心中途可能恰好有和原来的牌一样的情况,这种情况不返回,直到完完整整彻底变回初始状态也没找到想要的顺序。
这题说实话还不是很会,靠题解的每一天…有空再研究研究

#include <iostream>//考察map映射?
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <cstring>
#include <string>
#include <math.h>
using namespace std;
map<string,int>m;//相当于更高级的数组
string s1,s2,ans;
string s;
int h,step;
int dfs()
{
    s="";//表示申请了内存资源,但资源空间值为空。
    for(int i=0; i<h; i++)
    {
        s+=s2[i],s+=s1[i];//string字符串相加即拼接
    }
    step++;
    m[s]++;//代表此时s字符串的+1

    if(s==ans)
        return step;

    if(m[s]>1)//此处含义代表再次路过这个字符串,表示又回到原点
        return -1;

    s1="",s2="";
    for(int i=0; i<h; i++)
    {
        s1+=s[i];
    }
    for(int i=h; i<2*h; i++)
    {
        s2+=s[i];
    }
    dfs();

}
int main()
{
    int t;
    scanf("%d",&t);
    for(int i=1; i<=t; i++)
    {
        step=0;
        cin>>h;
        cin>>s1>>s2;
        cin>>ans;
        printf("%d %d\n",i,dfs());

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值