NC14548-B-逃脱(bfs)

该博客讨论了一个关于幼儿在幼儿园火场逃生的算法问题。题目描述了幼儿园地图的结构,包括空地、墙、起点、终点和火源,并规定了火势蔓延和幼儿移动的规则。算法通过模拟火势扩散和幼儿移动来判断是否能成功逃离。示例给出了三个测试用例,其中两个无法逃离,一个能在两步内逃离。博客内容涉及网格搜索、状态转移和最短路径寻找等算法知识。

B-逃脱

题号:NC14548
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld

题目描述 

这是mengxiang000和Tabris来到幼儿园的第四天,幼儿园老师在值班的时候突然发现幼儿园某处发生火灾,而且火势蔓延极快,老师在第一时间就发出了警报,位于幼儿园某处的mengxiang000和Tabris听到了火灾警报声的同时拔腿就跑,不知道两人是否能够逃脱险境?

幼儿园可以看成是一个N*M的图,在图中一共包含以下几种元素:

“.”:表示这是一块空地,是可以随意穿梭的。

“#”:表示这是一块墙,是不可以走到这上边来的,但是可以被火烧毁。

“S”:表示mengxiang000和Tabris所在位子。

“E”:表示幼儿园的出口。

“*”表示火灾发源地(保证输入只有一个火灾发源地)。

已知每秒有火的地方都会向周围八个格子(上下左右、左上、右上、左下、右下)蔓延火势.mengxiang000和Tabris每秒都可以选择周围四个格子(上下左右)进行移动。(假设两人这一秒行动完之后,火势才蔓延开)

根据已知条件,判断两人能否成功逃脱险境,如果可以,输出最短逃离时间,否则输出T_T。

 为了防止孩子们嬉戏中受伤,墙体是橡胶制作的,可以燃烧的哦。

输入描述:

第一行输入一个整数t,表示一共的测试数据组数。
第二行输入两个整数n,m,表示幼儿园的大小。
接下来n行,每行m个字符,表示此格子是什么元素。
t<=200
3<=n<=30
3<=M<=30
保证图中有一个起点,一个出口,一个火灾源处

输出描述:

每组数据输出一行,如果两人能够成功到达出口,那么输出最短逃离时间,否则输出T_T

示例1

输入

复制

3
5 5
*....
.....
..S#.
...E.
.....
5 5
...#*
..#S#
...##
....E
.....
5 5
.....
S....
..*#.
...E.
.....

输出

复制

2
T_T
T_T

说明

为了防止孩子们嬉戏中受伤,墙体是橡胶制作的,可以燃烧的哦。

备注:

为了防止孩子们嬉戏中受伤,墙体是橡胶制作的,可以燃烧的哦。
//#include <bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<string>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<list>
#include<set>
#include<iomanip>
#include<cstring>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<cassert>
#include<sstream>
#include<algorithm>
using namespace std;
const int mod=1e9+7;
typedef long long  ll;
#define ls (p<<1)
#define rs (p<<1|1)
#define mid (l+r)/2
#define over(i,s,t) for(register long long i=s;i<=t;++i)
#define lver(i,t,s) for(register long long i=t;i>=s;--i)
const int MAXN = 305;
const int INF = 0x3f3f3f3f;
const int N=5e4+7;
const int maxn=1e5+5;
const double EPS=1e-10;
const double Pi=3.1415926535897;
//inline double max(double a,double b){
//    return a>b?a:b;
//}
//inline double min(double a,double b){
//    return a<b?a:b;
//}

int xd[8] = {0, 1, 0, -1, 1, 1, -1, -1};
int yd[8] = {1, 0, -1, 0, -1, 1, -1, 1};

//void Fire(){
//    queue<node> p;
//    p.push({fx,fy,0});
//    memset(fire, -1, sizeof(fire));
//    fire[fx][fy]=0;
//    while(!p.empty()){
//        node temp=p.front();
//        p.pop();
//        for(int i=0;i<8;i++){
//            int x=temp.x+xd[i];
//            int y=temp.y+yd[i];
//            if(x<0||x>=n||y<0||y>=m||fire[x][y]!=-1){
//                continue;
//            }
//            fire[x][y]=temp.val+1;
//            p.push({x,y,temp.val+1});
//        }
//    }
//}
//int bfs(){
//    queue<node> p;
//    memset(vis, 0, sizeof(vis));
//    p.push({sx,sy,0});
//    while (!p.empty()) {
//        node temp=p.front();
//        vis[temp.x][temp.y]=1;
//        p.pop();
//        for(int i=0;i<4;i++){
//            int x=temp.x+xd[i];
//            int y=temp.y+yd[i];
//            if(x<0||x>=n||y<0||y>=m)  continue;
//            if(x==ex&&y==ey&&temp.val+1<=fire[x][y]) return temp.val+1;
//            if(vis[x][y]||temp.val+1>=fire[x][y]||a[x][y]=='#') continue;
//            p.push({x,y,temp.val+1});
//        }
//    }
//    return -1;
//}
int n,m,t;
char a[35][35];
int vis[35][35];
struct node{
    int x,y;
    int step;
};
int sx,sy,ex,ey,cx,cy;
int fire[35][35];
void Fire(int x,int y){
    memset(fire, -1, sizeof(fire));
    queue<node> p;
    p.push({x,y,0});
    while (!p.empty()) {
        node q=p.front();
        p.pop();
        for(int i=0;i<8;i++){
            int xx=q.x+xd[i];
            int yy=q.y+yd[i];
            if(xx<0||xx>=n||yy<0||yy>=m||fire[xx][yy]!=-1){
                continue;
            }
            p.push({xx,yy,q.step+1});
            fire[xx][yy]=q.step+1;
        }
    }
}
int bfs(int x,int y){
    queue<node> p;
    memset(vis, 0, sizeof(vis));
    p.push({x,y,0});

    while (!p.empty()) {
        node q=p.front();
        p.pop();
        vis[q.x][q.y]=1;
        for(int i=0;i<4;i++){
            int xx=q.x+xd[i];
            int yy=q.y+yd[i];
            if(xx<0||xx>n-1||yy<0||yy>m-1) continue;
            if(a[xx][yy]=='E'&&fire[xx][yy]>=q.step+1) return q.step+1;
            
            if(a[xx][yy]=='#'||vis[xx][yy]||fire[xx][yy]<=q.step+1) continue;
            p.push({xx,yy,q.step+1});
        }
    }
    return -1;
}
int main()
{
    cin>>t;
    while (t--) {
        cin>>n>>m;
        int ans=0;
        
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                cin>>a[i][j];
                if(a[i][j]=='*'){
                    cx=i;
                    cy=j;
                }
                if(a[i][j]=='S'){
                    sx=i;
                    sy=j;
                }
                if(a[i][j]=='E'){
                    ex=i;
                    ey=j;
                }
            }
        }
        Fire(cx, cy);
        ans=bfs(sx,sy);
        if(ans<0) cout<<"T_T"<<endl;
        else cout<<ans<<endl;
    }
}

### 关于人工智能中宽度优先搜索的练习题及其解法 #### 宽度优先搜索简介 宽度优先搜索(Breadth-First Search, BFS)是一种用于遍历或搜索树形或图结构的方法。该算法从根节点开始,先访问离根最近的所有节点,再依次深入下一层级直到找到目标节点或者遍历整个图形结构[^2]。 #### 练习题一:无权图最短路径问题 给定一个由多个城市组成的地图,其中每座城市之间可能存在道路连接。假设这些道路都是双向通行且长度相等,则可以通过构建一张邻接表来表示这个地图,并利用宽度优先搜索求得任意两城之间的最短距离。 ```python from collections import deque def bfs_shortest_path(graph, start, goal): visited = set() queue = deque([(start, 0)]) while queue: node, distance = queue.popleft() if node not in visited: visited.add(node) if node == goal: return distance for neighbor in graph[node]: if neighbor not in visited: queue.append((neighbor, distance + 1)) return None ``` 此段代码实现了基于队列的数据结构来进行广度优先探索的过程,在每次迭代时都会尝试获取当前层未被访问过的相邻顶点并将其加入到待处理列表当中去;当遇到终点时返回所经过的距离数作为结果输出。 #### 练习题二:迷宫逃脱游戏 在一个二维网格上存在起点S和终点E的位置标记以及障碍物X分布情况下的简单迷宫环境里,通过执行宽度优先策略寻找一条通往出口的有效路线。 ```python def escape_maze(maze): directions = [(0,-1), (0,1), (-1,0), (1,0)] # 左右上下四个方向移动方式定义 rows, cols = len(maze), len(maze[0]) queue = deque([find_start_position(maze)]) # 找到起始位置坐标(x,y),初始化队列 steps = [[None]*cols for _ in range(rows)] steps[queue[-1][0]][queue[-1][1]] = 0 while queue: row, col = queue.popleft() if maze[row][col]=='E': break for d_row,d_col in directions: next_r,next_c=row+d_row,col+d_col if is_valid_move(next_r,next_c,maze) and steps[next_r][next_c]==None : queue.append((next_r,next_c)) steps[next_r][next_c]=steps[row][col]+1 path=reconstruct_path(steps) return path def find_start_position(maze): for i,line in enumerate(maze): try: j=line.index('S') return (i,j) except ValueError: continue def is_valid_move(r,c,maze): R,C=len(maze),len(maze[0]) return all([ r>=0, c>=0, r<R , c<C , maze[r][c]!='X' ]) def reconstruct_path(step_matrix): end=find_end_position(step_matrix) current=end[:] path=[current] while step_matrix[current[0]][current[1]]: prev_step=step_matrix[current[0]][current[1]] neighbors=get_neighbors(current) for n in neighbors: if step_matrix[n[0]][n[1]]==prev_step-1: current=n[:] path.insert(0,current) break return path[:-1] def get_neighbors(pos): dirs=[(-1,0),(1,0),(0,-1),(0,1)] res=[] for dr,dc in dirs: nr,nc=pos[0]+dr,pos[1]+dc res.append((nr,nc)) return res def find_end_position(matrix): for ri,row in enumerate(matrix): for ci,val in enumerate(row): if val!=None:return (ri,ci) maze=[ ['S','.','.','#'], ['#','.','E','#'], ['.','.','.','#'], ['#','#','#','#'] ] print(escape_maze(maze)) #[[(0, 0), (0, 1), (1, 1), (2, 1)], ... ] ``` 上述例子展示了如何应用宽度优先搜索解决实际场景中的导航类问题——即在限定条件下规划最优行动方案以达到既定目的。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

郭晋龙

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

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

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

打赏作者

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

抵扣说明:

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

余额充值