Three good friends
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 97 | Accepted: 35 |
Description
FF,JJ and QQ are three good friends. But their house are very far away form each others.Their want to build a road so that their houses could connect together.
"F" on the map indicate FF's house,"J" indicates JJ's house ,"Q" indicates QQ's house,"." indicates there could build road on it. "X" indicates a barrier,there can't build road.
Now, tell you the information of the map,please help three lovely girls to calculate the minimum cost to build the road;
"F" on the map indicate FF's house,"J" indicates JJ's house ,"Q" indicates QQ's house,"." indicates there could build road on it. "X" indicates a barrier,there can't build road.
Now, tell you the information of the map,please help three lovely girls to calculate the minimum cost to build the road;
Input
The first line with two numbers n and m ( 0 < n , m <= 100 )
stands for the size of the map;then n lines follow ,each line with m characters.
There are exact one "J",one "X" and one "F".
stands for the size of the map;then n lines follow ,each line with m characters.
There are exact one "J",one "X" and one "F".
Output
If could build please output the minimum cost;others output"Impossible";
Sample Input
3 3 F.X ... J.Q 3 3 F.. ..X JXQ
Sample Output
2 Impossible#include<stdio.h> #include<string.h> #include<queue> #include<iostream> #define M 110 #define INF 100000000 using namespace std; int n,m; int fx,fy,jx,jy,qx,qy; char map[M][M]; int disf[M][M]; int disj[M][M]; int disq[M][M]; bool v[M][M]; int dir[4][2]={1,0,-1,0,0,1,0,-1}; struct node { int x,y; }que[M*M]; void bfs(int a,int b,int dis[][M]) { int l=0,r=0; int i,p,k; memset(v,false,sizeof(v)); que[r].x=a; que[r++].y=b; v[a][b]=true; dis[a][b]=0; while(l<r) { int x=que[l].x; int y=que[l++].y; for(k=0;k<4;k++) { int xx=x+dir[k][0]; int yy=y+dir[k][1]; if(!v[xx][yy]&&map[xx][yy]!='X'&&xx>0&&xx<=n&&yy>0&&yy<=m) { v[xx][yy]=true; dis[xx][yy]=dis[x][y]+1; que[r].x=xx; que[r++].y=yy; } } } } void solve(int i,int j,char c) { if(c=='F') { fx=i;fy=j; return; } if(c=='Q') { qx=i;qy=j; return; } if(c=='J') { jx=i;jy=j; return; } } int main() { int i,j; int minn; while(scanf("%d%d%*c",&n,&m)!=EOF) { for(i=0;i<=n;i++) for(j=0;j<=m;j++) { map[i][j]=0; disf[i][j]=disj[i][j]=disq[i][j]=INF; } for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { scanf("%c",&map[i][j]); solve(i,j,map[i][j]); } getchar(); } bfs(fx,fy,disf); bfs(jx,jy,disj); bfs(qx,qy,disq); minn=INF; for(i=1;i<=n;i++) for(j=1;j<=m;j++) { if(map[i][j]=='X') continue; if(disf[i][j]==INF||disj[i][j]==INF||disq[i][j]==INF) continue; int tmp=disf[i][j]+disj[i][j]+disq[i][j]; if(tmp<minn) minn=tmp; } if(minn!=INF) printf("%d\n",minn-2); else printf("Impossible\n"); } return 0; }