题目大意:
这道题说的是,求出从Y开始到'@'和从M开始到'@'的最短的距离的和是多少。
解题思路:
一开始记录Y的位置,然后记录M的位置,求出Y到每个‘@’的距离,求出M到每个'@'的最短的距离
然后依次枚举每个@,求出两者和的最小值。
代码:
1 # include<cstdio> 2 # include<iostream> 3 # include<queue> 4 # include<cstring> 5 6 using namespace std; 7 8 # define inf 99999999 9 # define MAX 233 10 11 12 struct node 13 { 14 int x,y; 15 }; 16 17 queue<node>Q; 18 19 20 int x1,y11,x2,y2; 21 char a[MAX][MAX]; 22 int book[MAX][MAX][2]; 23 int nxt[4][2] = {{1,0},{0,-1},{-1,0},{0,1} }; 24 int n,m; 25 26 27 int can_move ( int x,int y,int tag ) 28 { 29 if ( x>=0&&x<n&&y>=0&&y<m&&book[x][y][tag]==0&&a[x][y]!='Y'&&a[x][y]!='#'&&a[x][y]!='M' ) 30 return 1; 31 else 32 return 0; 33 } 34 35 36 void init() 37 { 38 while ( !Q.empty() ) 39 { 40 Q.pop(); 41 } 42 } 43 44 void bfs ( node start,int tag ) 45 { 46 init(); 47 Q.push(start); 48 while ( !Q.empty() ) 49 { 50 node now = Q.front(); 51 Q.pop(); 52 for ( int i = 0;i < 4;i++ ) 53 { 54 int tx = now.x+nxt[i][0], ty = now.y+nxt[i][1]; 55 if ( can_move ( tx,ty,tag ) ) 56 { 57 book[tx][ty][tag] = book[now.x][now.y][tag]+1; 58 node newnode; 59 newnode.x = tx; newnode.y = ty; 60 Q.push(newnode); 61 } 62 } 63 } 64 return; 65 } 66 67 68 69 int main(void) 70 { 71 while ( scanf("%d%d",&n,&m)!=EOF ) 72 { 73 for ( int i = 0; i < n;i++ ) 74 scanf("%s",a[i]); 75 for ( int i = 0;i < n;i++ ) 76 { 77 for ( int j = 0;j < m;j++ ) 78 { 79 if ( a[i][j]=='Y' ) 80 { 81 x1 = i; y11 = j; 82 } 83 if ( a[i][j]=='M' ) 84 { 85 x2 = i; y2 = j; 86 } 87 } 88 } 89 90 node start; 91 start.x = x1; start.y = y11; 92 bfs(start,0); 93 start.x = x2; start.y = y2; 94 bfs(start,1); 95 int res = inf; 96 for ( int i = 0;i < n;i++ ) 97 { 98 for ( int j = 0;j < m;j++ ) 99 { 100 if ( a[i][j]=='@' ) 101 { 102 if ( book[i][j][0]!=0&&book[i][j][1]!=0 ) 103 { 104 res = min(res,book[i][j][0]+book[i][j][1]); 105 } 106 } 107 } 108 } 109 printf("%d ",res*11); 110 memset(book,0,sizeof(book)); 111 } 112 113 114 return 0; 115 }