博客
关于我
POJ 2312Battle City(BFS-priority_queue 或者是建图spfa)
阅读量:432 次
发布时间:2019-03-06

本文共 2479 字,大约阅读时间需要 8 分钟。

1 /* 2     bfs搜索!要注意的是点与点的权值是不一样的哦! 3    空地到空地的步数是1, 空地到墙的步数是2(轰一炮+移过去) 4    所以用到优先队列进行对当前节点步数的更新!        5 */ 6 #include
7 #include
8 #include
9 #include
10 #include
11 using namespace std;12 13 int n, m;14 char map[305][305];15 16 struct node{17 int x, y;18 int step;19 node(){}20 node(int x, int y, int step){21 this->x=x;22 this->y=y;23 this->step=step;24 }25 };26 int dir[4][2]={0, 1, 1, 0, -1, 0, 0, -1};27 28 bool operator >(node a, node b){29 return a.step > b.step;30 }31 32 priority_queue
, greater
>q;33 34 bool bfs(){35 while(!q.empty()){36 node cur=q.top();37 q.pop();38 if(map[cur.x][cur.y]=='T'){39 cout<
<
>n>>m && (n || m)){64 for(int i=1; i<=n; ++i){65 cin>>(map[i]+1);66 map[i][0]=map[i][m+1]='R';67 for(int j=1; j<=m; ++j){68 if(map[i][j]=='Y'){69 q.push(node(i, j, 0));70 map[i][j]='R';71 }72 map[0][j]=map[n+1][j]='R';73 }74 }75 if(!bfs())76 cout<<"-1"<
1 /* 2     将map[i][j]映射到 i*m+j的节点上,建立节点与节点之间的权值的关系! 3     B->B的权值为1, E->B的权值为2, S<->...  R<->... 的权值为INF(也就是没有边存在)  4     在注意一点就是B->E的权值是 1,因为如果到B了,说明炮弹已经将墙轰掉了! 5      6     建立好图之后,那么就是求源点到终点的最短的距离了! 7     这里采用的spfa算法!  8 */ 9 10 #include
11 #include
12 #include
13 #include
14 #include
15 #include
16 #define N 9001017 #define INF 0x3f3f3f3f18 using namespace std;19 struct node{20 int to;21 int dist;22 node(){}23 24 node(int to, int dist){25 this->to=to;26 this->dist=dist;27 }28 };29 vector
g[N];30 int vis[N], d[N];31 char map[305][305];32 int dir[4][2]={0, 1, 1, 0, -1, 0, 0, -1};33 int ss, tt;34 int n, m;35 queue
q;36 bool spfa(){37 q.push(ss);38 memset(vis, 0, sizeof(vis));39 vis[ss]=1;40 memset(d, 0x3f, sizeof(d));41 d[ss]=0;42 while(!q.empty()){43 int u=q.front(); q.pop();44 vis[u]=0;45 int len=g[u].size();46 for(int i=0; i
d[u] + g[u][i].dist){49 d[v] = d[u] + g[u][i].dist;50 51 if(!vis[v]){52 q.push(v);53 vis[v]=1; 54 }55 }56 }57 }58 if(d[tt]==INF) return false;59 return true;60 }61 62 int main(){63 while(cin>>n>>m && (n||m)){64 for(int i=0; i
>map[i];66 for(int i=0; i
=n || y<0 || y>=m) continue;76 if(map[x][y]=='R' || map[x][y]=='S') continue;77 78 int to = x*m+y, dist=1;79 if(map[i][j]=='B' || map[x][y]=='B') dist=2;80 if(map[i][j]=='B' && map[x][y]!='B') dist=1;81 g[from].push_back(node(to, dist));82 83 }84 }85 if(!spfa())86 cout<<"-1"<

 

 

转载地址:http://oghuz.baihongyu.com/

你可能感兴趣的文章
Nginx gateway集群和动态网关
查看>>
Nginx Location配置总结
查看>>
Nginx log文件写入失败?log文件权限设置问题
查看>>
Nginx Lua install
查看>>
nginx net::ERR_ABORTED 403 (Forbidden)
查看>>
Nginx SSL 性能调优
查看>>
Nginx SSL私有证书自签,且反代80端口
查看>>
Nginx upstream性能优化
查看>>
Nginx 中解决跨域问题
查看>>
nginx 代理解决跨域
查看>>
Nginx 做负载均衡的几种轮询策略分析
查看>>
Nginx 动静分离与负载均衡的实现
查看>>
Nginx 反向代理 MinIO 及 ruoyi-vue-pro 配置 MinIO 详解
查看>>
nginx 反向代理 转发请求时,有时好有时没反应,产生原因及解决
查看>>
Nginx 反向代理+负载均衡
查看>>
Nginx 反向代理解决跨域问题
查看>>
Nginx 反向代理配置去除前缀
查看>>
nginx 后端获取真实ip
查看>>
Nginx 多端口配置和访问异常问题的排查与优化
查看>>
Nginx 如何代理转发传递真实 ip 地址?
查看>>