题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2612
BFS搜索 目标地 并记录下来 之后再判断两段路程之和
代码:
1 #include <stdio.h> 2 #include <string.h> 3 #include <math.h> 4 #include <algorithm> 5 #include <iostream> 6 #include <ctype.h> 7 #include <iomanip> 8 #include <queue> 9 #include <stdlib.h> 10 using namespace std; 11 12 #define INF 0x3f3f3f3f 13 #define N 220 14 #define M 220 15 int n,m; 16 char mp[N][M]; 17 int vis1[N][M],vis2[N][M]; 18 int ans1[N][M],ans2[N][M]; 19 int dx[4]={0,0,1,-1}; 20 int dy[4]={1,-1,0,0}; 21 22 struct node 23 { 24 int x,y; 25 int t; 26 }; 27 28 node g1,g2; 29 void getMp() 30 { 31 for(int i=0; i<n; i++){ 32 for(int j=0; j<m; j++){ 33 cin>>mp[i][j]; 34 if(mp[i][j]=='Y'){ 35 g1.x=i; 36 g1.y=j; 37 g1.t=0; 38 vis1[i][j]=1; 39 } 40 if(mp[i][j]=='M'){ 41 g2.x=i; 42 g2.y=j; 43 g2.t=0; 44 vis2[i][j]=1; 45 } 46 } 47 } 48 } 49 50 void bfs1() 51 { 52 queue<node> q; 53 while(!q.empty()) 54 q.pop(); 55 q.push(g1); 56 while(!q.empty()){ 57 node f1; 58 f1=q.front(); 59 q.pop(); 60 for(int i=0; i<4; i++){ 61 node f2; 62 f2.x=f1.x+dx[i]; 63 f2.y=f1.y+dy[i]; 64 f2.t=f1.t; 65 if(0<=f2.x&&f2.x<n&&0<=f2.y&&f2.y<m&&!vis1[f2.x][f2.y]&&mp[f2.x][f2.y]!='#'){ 66 f2.t++; 67 if(mp[f2.x][f2.y]=='@'){ 68 ans1[f2.x][f2.y]=f2.t; 69 } 70 vis1[f2.x][f2.y]=1; 71 q.push(f2); 72 } 73 } 74 } 75 } 76 77 void bfs2() 78 { 79 queue<node> q; 80 while(!q.empty()) 81 q.pop(); 82 q.push(g2); 83 while(!q.empty()){ 84 node f1; 85 f1=q.front(); 86 q.pop(); 87 for(int i=0; i<4; i++){ 88 node f2; 89 f2.x=f1.x+dx[i]; 90 f2.y=f1.y+dy[i]; 91 f2.t=f1.t; 92 if(0<=f2.x&&f2.x<n&&0<=f2.y&&f2.y<m&&!vis2[f2.x][f2.y]&&mp[f2.x][f2.y]!='#'){ 93 f2.t++; 94 if(mp[f2.x][f2.y]=='@'){ 95 ans2[f2.x][f2.y]=f2.t; 96 } 97 vis2[f2.x][f2.y]=1; 98 q.push(f2); 99 } 100 } 101 } 102 } 103 104 int main() 105 { 106 while(~scanf("%d %d",&n,&m)){ 107 memset(ans1,-1,sizeof(ans1)); 108 memset(ans2,-1,sizeof(ans2)); 109 memset(vis1,0,sizeof(vis1)); 110 memset(vis2,0,sizeof(vis2)); 111 getMp(); 112 bfs1(); 113 bfs2(); 114 int min=INF; 115 for(int i=0;i<n;i++) 116 for(int j=0;j<m;j++) 117 { 118 if(ans1[i][j]+ans2[i][j]<min&&ans1[i][j]+ans2[i][j]>0) 119 { 120 min=ans1[i][j]+ans2[i][j]; 121 } 122 } 123 printf("%d ",min*11); 124 } 125 }