本文共 2479 字,大约阅读时间需要 8 分钟。
1 /* 2 bfs搜索!要注意的是点与点的权值是不一样的哦! 3 空地到空地的步数是1, 空地到墙的步数是2(轰一炮+移过去) 4 所以用到优先队列进行对当前节点步数的更新! 5 */ 6 #include7 #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 #include11 #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/