广度优先搜索(BFS)例题

本文介绍了一个基于广度优先搜索(BFS)算法的游戏路径寻找问题。通过一个简化版的“BattleCity”游戏地图实例,详细解释了如何使用BFS算法找到从起点到目标点所需的最少步数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BFS样例模板

以这道题为例:

Battle City

Many of us had played the game “Battle city” in our childhood, and some people (like me) even often play it on computer now.

What we are discussing is a simple edition of this game. Given a map that consists of empty spaces, rivers, steel walls and brick walls only. Your task is to get a bonus as soon as possible suppose that no enemies will disturb you (See the following picture).

Your tank can’t move through rivers or walls, but it can destroy brick walls by shooting. A brick wall will be turned into empty spaces when you hit it, however, if your shot hit a steel wall, there will be no damage to the wall. In each of your turns, you can choose to move to a neighboring (4 directions, not 8) empty space, or shoot in one of the four directions without a move. The shot will go ahead in that direction, until it go out of the map or hit a wall. If the shot hits a brick wall, the wall will disappear (i.e., in this turn). Well, given the description of a map, the positions of your tank and the target, how many turns will you take at least to arrive there?
Input
The input consists of several test cases. The first line of each test case contains two integers M and N (2 <= M, N <= 300). Each of the following M lines contains N uppercase letters, each of which is one of ‘Y’ (you), ‘T’ (target), ‘S’ (steel wall), ‘B’ (brick wall), ‘R’ (river) and ‘E’ (empty space). Both ‘Y’ and ‘T’ appear only once. A test case of M = N = 0 indicates the end of input, and should not be processed.
Output
For each test case, please output the turns you take at least in a separate line. If you can’t arrive at the target, output “-1” instead.
Sample Input
3 4
YBEB
EERE
SSTE
0 0
Sample Output
8

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
#include<cmath>
#include<cstdio>
#define ll long long
using namespace std;
const int MAXN=310;
int a1,b1,mex,mey,tx,ty,flag,r[MAXN][MAXN];
char str[MAXN][MAXN];
int r1[2][4]={{0,0,1,-1},{1,-1,0,0}};
struct node{
    int x,y,step;
    friend bool operator<(node a,node b){
        return a.step>b.step;
    }
};
 
void BFS(int mex,int mey){
    priority_queue<node> p;
    flag=0;
    node now,next;
    now.x=mex;
    now.y=mey;
    now.step=0;
    p.push(now);
    while(!p.empty()){
        next=p.top();
        p.pop();
        if(str[next.x][next.y]=='T'){
            flag=1;
            break;
        }
        for(int i=0;i<4;i++){
            now.x=next.x+r1[0][i];
            now.y=next.y+r1[1][i];
            if(now.x>=0 && now.x<a1 && now.y>=0 && now.y<b1 && str[now.x][now.y]!='S' && str[now.x][now.y]!='R' && !r[now.x][now.y]){
                if(str[now.x][now.y]=='B'){
                    now.step=next.step+2;
                }
                else{
                    now.step=next.step+1;
                }
                r[now.x][now.y]=1;
                p.push(now);
            }
        }
    }
    if(flag){
        printf("%d\n",next.step);
    }
    else{
        printf("%d\n",-1);
    }
}
int main(){
    while(scanf("%d%d",&a1,&b1)!=EOF&&(a1||b1)){
        memset(r,0,sizeof(r));
        memset(str,0,sizeof(str));
        for(int i=0;i<a1;i++){
            getchar();
            for(int j=0;j<b1;j++){
                scanf("%c",&str[i][j]);
                if(str[i][j]=='Y'){
                    mex=i;
                    mey=j;
                }
            }
        }
        BFS(mex,mey);
    }
    return 0;
}
### 深度优先搜索(DFS)和广度优先搜索BFS例题及算法示例 #### 深度优先搜索(DFS)例题 深度优先搜索是一种从某个顶点开始,沿着一条路径尽可能深入探索的算法。以下是一个经典的 DFS 例题:迷宫问题。 **问题描述** 给定一个二维数组表示的迷宫,其中 `0` 表示可以通过的路径,`1` 表示障碍物。起点为 `(0, 0)`,终点为 `(n-1, m-1)`,求是否存在一条从起点到终点的路径。 **算法实现** 使用递归实现 DFS,标记已访问过的节点以避免重复访问。 ```python # 定义方向向量 dx = [0, 1, 0, -1] dy = [1, 0, -1, 0] def is_valid(x, y, n, m, maze, visited): return 0 <= x < n and 0 <= y < m and maze[x][y] == 0 and not visited[x][y] def dfs(x, y, n, m, maze, visited): if x == n - 1 and y == m - 1: # 到达终点 return True visited[x][y] = True for i in range(4): # 尝试四个方向 nx, ny = x + dx[i], y + dy[i] if is_valid(nx, ny, n, m, maze, visited) and dfs(nx, ny, n, m, maze, visited): return True return False # 示例迷宫 maze = [ [0, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 0], [0, 1, 1, 0] ] n, m = len(maze), len(maze[0]) visited = [[False] * m for _ in range(n)] result = dfs(0, 0, n, m, maze, visited) print("是否存在路径:", result) ``` 上述代码中,`dfs` 函数递归地尝试从当前节点移动到相邻节点,直到找到终点或所有可能路径都被尝试完毕[^4]。 --- #### 广度优先搜索BFS例题 广度优先搜索是一种从某个顶点开始,逐层遍历图或树的算法。以下是一个经典的 BFS 例题:最短路径问题。 **问题描述** 同样使用迷宫问题作为例子,但这次要求找到从起点到终点的最短路径长度。 **算法实现** 使用队列实现 BFS,记录每个节点的访问状态以及到达该节点的距离。 ```python from collections import deque def bfs(maze): n, m = len(maze), len(maze[0]) queue = deque([(0, 0, 0)]) # (x, y, distance) visited = [[False] * m for _ in range(n)] visited[0][0] = True while queue: x, y, dist = queue.popleft() if x == n - 1 and y == m - 1: # 到达终点 return dist for i in range(4): nx, ny = x + dx[i], y + dy[i] if is_valid(nx, ny, n, m, maze, visited): visited[nx][ny] = True queue.append((nx, ny, dist + 1)) return -1 # 无法到达终点 # 使用相同的迷宫 result = bfs(maze) print("最短路径长度:", result) ``` 在 BFS 中,通过队列逐步扩展每一层的节点,确保首次到达终点时的路径是最短的[^3]。 --- ### 总结 - 深度优先搜索适用于需要穷尽所有可能性的问题,例如判断连通性或寻找任意路径。 - 广度优先搜索适用于寻找最短路径或最小步数的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值