洛谷P2298 Mzc和男家丁的游戏

题目链接:https://www.luogu.com.cn/problem/P2298

在本质上是一道bfs迷宫的模板题

其实bfs的大部分方式还是有迹可循的,这里提供一种bfs的思路:

 1 int bfs(int sx,int sy)
 2 {
 3   q.push((Pos){sx,sy}); //起点加入队列
 4   vis[sx][sy]=true; //标记
 5   while(!q.empty()) 
 6   {
 7       x=q.front().x;
 8       y=q.front().y; //获取起始坐标
 9       q.pop(); //弹出队列
10       if(符合条件) return ans(答案); 
11       for(int i=0;i<走法;i++)
12       {
13           tx=x+dx[i];
14           ty=y+dy[i];
15           if(符合条件) continue;
16           if(符合条件) continue; //符合条件跳过循环
17           /*
18                          可行,执行该部分语句
19                                                     */
20           q.push((Pos){tx,ty}); //加入队列
21       }
22   }
23 }

本题需要注意的是,对于剪枝操作和dis数组的运算

参考代码如下:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,m;//行数和列数
 4 int ans;
 5 int dis[2010][2010];//distance表示距离
 6 bool vis[2010][2010];//标记数组
 7 int dx[4]={-1,0,1,0};//从左往右对横坐标的搜索 
 8 int dy[4]={0,-1,0,1};//对纵坐标的搜素 
 9 int sx,sy;//开始的坐标即m的坐标 
10 char ch[2010][2010];
11 struct node
12 {
13     int x;
14     int y;
15 };
16 int bfs(int bx,int by)
17 {
18     vis[bx][by]==true;
19     queue<node>q;
20     node start,next;
21     start.x=bx;
22     start.y=by;
23     q.push(start);//入队 
24     while(!q.empty())
25     {
26         start=q.front();//返回队首元素但不删除
27         q.pop();//出队
28         if(ch[start.x][start.y]=='d')
29         return dis[start.x][start.y];//剪枝 
30         for(register int i=0;i<4;i++)
31         {
32             next.x=start.x+dx[i];
33             next.y=start.y+dy[i];
34             if(next.x<=0||next.x>n||next.y<=0||next.y>m)
35             continue;//不满足条件跳过取
36             if(vis[next.x][next.y]==true||ch[next.x][next.y]=='#')
37             continue;
38              dis[next.x][next.y]=dis[start.x][start.y]+1;//下一个方向 
39              vis[next.x][next.y]=true;//表示已经走过了;
40              q.push(next);//下一个方向入队 
41          } 
42     }
43     return -1; 
44 }
45 int main()
46 {
47     ios::sync_with_stdio(false);
48     cin>>n>>m;
49     for(register int i=1;i<=n;i++)
50     {
51         for(register int j=1;j<=m;j++)
52         {
53             cin>>ch[i][j];
54             if(ch[i][j]=='m')
55             {
56                 sx=i;
57                 sy=j;
58             }
59         }
60      } 
61      ans=bfs(sx,sy);
62      if(ans==-1)
63      cout<<"No Way!"<<endl;
64      else
65      cout<<ans<<endl;
66     return 0; 
67 }

 

posted @ 2022-03-18 16:56  江上舟摇  阅读(46)  评论(0编辑  收藏  举报