Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=2612
BFS search target and record and then judge the sum of two distances
Code:
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>Ten using namespacestd; One A #defineINF 0x3f3f3f3f - #defineN 220 - #defineM 220 the intn,m; - CharMp[n][m]; - intVis1[n][m],vis2[n][m]; - intAns1[n][m],ans2[n][m]; + intdx[4]={0,0,1,-1}; - intdy[4]={1,-1,0,0}; + A structnode at { - intx, y; - intT; - }; - - node g1,g2; in voidgetmp () - { to for(intI=0; i<n; i++){ + for(intj=0; j<m; J + +){ -Cin>>Mp[i][j]; the if(mp[i][j]=='Y'){ *g1.x=i; $g1.y=J;Panax Notoginsengg1.t=0; -vis1[i][j]=1; the } + if(mp[i][j]=='M'){ Ag2.x=i; theg2.y=J; +g2.t=0; -vis2[i][j]=1; $ } $ } - } - } the - voidBFS1 ()Wuyi { theQueue<node>Q; - while(!q.empty ()) Wu Q.pop (); - Q.push (G1); About while(!Q.empty ()) { $ node F1; -f1=Q.front (); - Q.pop (); - for(intI=0; i<4; i++){ A node F2; +f2.x=f1.x+Dx[i]; thef2.y=f1.y+Dy[i]; -f2.t=f1.t; $ if(0<=f2.x&&f2.x<n&&0<=f2.y&&f2.y<m&&!vis1[f2.x][f2.y]&&mp[f2.x][f2.y]!='#'){ thef2.t++; the if(mp[f2.x][f2.y]=='@'){ theans1[f2.x][f2.y]=f2.t; the } -vis1[f2.x][f2.y]=1; in Q.push (F2); the } the } About } the } the the voidBFS2 () + { -Queue<node>Q; the while(!q.empty ())Bayi Q.pop (); the Q.push (G2); the while(!Q.empty ()) { - node F1; -f1=Q.front (); the Q.pop (); the for(intI=0; i<4; i++){ the node F2; thef2.x=f1.x+Dx[i]; -f2.y=f1.y+Dy[i]; thef2.t=f1.t; the if(0<=f2.x&&f2.x<n&&0<=f2.y&&f2.y<m&&!vis2[f2.x][f2.y]&&mp[f2.x][f2.y]!='#'){ thef2.t++;94 if(mp[f2.x][f2.y]=='@'){ theans2[f2.x][f2.y]=f2.t; the } thevis2[f2.x][f2.y]=1;98 Q.push (F2); About } - } 101 }102 }103 104 intMain () the {106 while(~SCANF ("%d%d",&n,&m)) {107memset (ans1,-1,sizeof(ans1));108memset (ans2,-1,sizeof(ANS2));109memset (Vis1,0,sizeof(VIS1)); thememset (Vis2,0,sizeof(VIS2));111 getmp (); the BFS1 ();113 BFS2 (); the intmin=INF; the for(intI=0; i<n;i++) the for(intj=0; j<m;j++) 117 { 118 if(ans1[i][j]+ans2[i][j]<min&&ans1[i][j]+ans2[i][j]>0) 119 { -min=ans1[i][j]+Ans2[i][j]; 121 } 122 }123printf"%d\n", min* One); 124 } the}
Find A (BFS)