博客
关于我
POJ 2312Battle City(BFS-priority_queue 或者是建图spfa)
阅读量:419 次
发布时间: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/

你可能感兴趣的文章
Spring Security 实战干货:理解AuthenticationManager
查看>>
Java对象转JSON时如何动态的增删改查属性
查看>>
Python 面向对象进阶
查看>>
Linux常用统计命令之wc
查看>>
Git安装及使用以及连接GitHub方法详解
查看>>
docker容器与虚拟机的区别
查看>>
shell脚本里使用echo输出颜色
查看>>
Python2跟Python3的区别
查看>>
并发编程——IO模型详解
查看>>
Java之封装,继承,多态
查看>>
wait()与notify()
查看>>
使用js打印时去除页眉页脚
查看>>
Spring security OAuth2.0认证授权学习第二天(基础概念-RBAC)
查看>>
ORA-00904: "FILED_TYPE": 标识符无效
查看>>
数据仓库系列之维度建模
查看>>
Scala教程之:函数式的Scala
查看>>
java中DelayQueue的使用
查看>>
线程stop和Interrupt
查看>>
Android中定时执行任务的3种实现方法
查看>>
nodejs中npm常用命令
查看>>