Problem Description
Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.
Input
The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’ express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF
Output
For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.
Sample Input
4 4
Y.#@
…
.#…
@…M
4 4
Y.#@
…
.#…
@#.M
5 5
Y…@.
.#…
.#…
@…M.
#…#
Sample Output
66
88
66
这道题的大致意思给你n*m的矩阵,其中矩阵中的‘Y’,‘M’代表起点,‘@
’代表终点,‘ . ’为道路,‘ # ’为阻碍,要求你找到一个‘@’使得其到Y,M的和最小。
思路:我先将Y到各个‘@’的距离先用bfs搜出来,用dis数组存放,然后再将M到各个‘@'距离加到dis数组的相应位置上,找到最小的值。
#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn =205;
const int inf=0x3f3f3f3f;
int me[4][2]={{1,0},{-1,0},{0,1},{0,-1}};//向上,下,左,右移动
int min1;//存放最短距离
char ah[maxn][maxn];//存放地图
int dp[maxn][maxn];//该点是否已经走过
int n;int m;//行,列
int ans;int cnt;//cnt代表进行几次bfs
int de;//代表@的个数,@不仅仅只有一个
int dis[maxn][maxn];//存放距离
struct node{
int x;int y;int step; //step代表距离
}st1,st2;
bool ok(int x,int y){//判断(x,y)点 是否可用
if(x<1||x>n||y<1||y>m)return false;
else if(dp[x][y]==1)return false;
else if(ah[x][y]=='Y'||ah[x][y]=='M'||ah[x][y]=='#')return false;
else if(dp[x][y]==0&&ah[x][y]=='.')return true;
else if(dp[x][y]==0&&ah[x][y]=='@')return true;
}
void bfs(int x,int y){
dp[x][y]=1;
node we;we.step=0;
we.x=x;we.y=y;
queue<node>q;
q.push(we);
while(!q.empty()){
node t=q.front();q.pop();
node newnode;
if(ah[t.x][t.y]=='@'){
dis[t.x][t.y]=dis[t.x][t.y]+t.step;
if(cnt==2&&de!=1){
min1=min(dis[t.x][t.y],min1);
}
else if(de==1)min1=dis[t.x][t.y];
}
for(int i=0;i<4;i++){
int fx=t.x+me[i][0];
int fy=t.y+me[i][1];
if(ok(fx,fy)){
newnode.x=fx;
newnode.y=fy;
newnode.step=t.step+1;
q.push(newnode);
dp[fx][fy]=1;
}
}
}
cnt++;
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
de=0;
for(int i=1;i<=n;i++){
getchar();
for(int j=1;j<=m;j++){
scanf("%c",&ah[i][j]);
if(ah[i][j]=='Y'){
st1.x=i;st1.y=j;
}
if(ah[i][j]=='M'){
st2.x=i;st2.y=j;
}
if(ah[i][j]=='@')de++;
}
}
min1=inf;
memset(dis,0,sizeof dis);
ans=0;cnt=1;//cnt代表搜索的次数
memset(dp,0,sizeof dp);
bfs(st1.x,st1.y);
memset(dp,0,sizeof dp);
bfs(st2.x,st2.y);
printf("%d\n",min1*11);
}
}
道阻且长
自己选的路 跪着也要走完