Description
Input
Output
Sample Input
2 6 5 ##### #A#A## # # A# #S ## ##### 7 7 ##### #AAA### # A# # S ### # # #AAA### #####
Sample Output
8 11
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <queue> #include <stack> #include <algorithm> #define LL long long #define INF 0x3f3f3f3f #define MAX 51 using namespace std; struct node { int x,y; int step; }; char str[MAX][MAX]; int ant; int Map[MAX*MAX][MAX*MAX]; int a[MAX][MAX]; int eveco[MAX*MAX]; bool vis[MAX*MAX]; bool flag[MAX][MAX]; int n,m; int top; int Dir[][2] = {{0,1},{1,0},{-1,0},{0,-1}}; void BFS(int x,int y) { memset(flag,false,sizeof(flag)); queue<node >que; node b,c; b.x = x; b.y = y; b.step = 0; flag[x][y] = true; que.push(b); while(!que.empty()) { b = que.front(); que.pop(); if(a[b.x][b.y] != 0) { Map[a[x][y]][a[b.x][b.y]] = b.step; } for(int i=0; i<4; i++) { c.x = b.x + Dir[i][0]; c.y = b.y + Dir[i][1]; c.step = b.step + 1; if(!flag[c.x][c.y] && str[c.x][c.y] != '#') { flag[c.x][c.y] = true; que.push(c); } } } } int Prim() { int cost = 0; memset(vis,false,sizeof(vis)); for(int i=1; i<=top; i++) { eveco[i] = Map[1][i]; } eveco[1] = 0; vis[1] = true; for(int i=1; i<top; i++) { int m = INF; int pos; for(int j=1; j<=top; j++) { if(!vis[j] && m > eveco[j]) { pos = j; m = eveco[j]; } } cost += m; vis[pos] = true; for(int j=1; j<=top; j++) { if(!vis[j] && eveco[j] > Map[pos][j]) { eveco[j] = Map[pos][j]; } } } return cost; } int main() { //freopen("in.txt","r",stdin); int T; scanf("%d",&T); while(T--) { top = 0; memset(a,0,sizeof(a)); scanf("%d%d",&n,&m); gets(str[0]); for(int i=1; i<=n; i++) { gets(str[i]); for(int j=1; j<=m; j++) { if(str[i][j] == 'S' || str[i][j] == 'A') { a[i][j] = ++top; } } } // for(int i=1;i<=top;i++) // { // for(int j=1;j<=top;j++) // { // if(j == top) // cout<<a[i][j]<<endl; // else // cout<<a[i][j]<<" "; // } // } for(int i=1; i<=n; i++) { for(int j=1; j<=m; j++) { if(a[i][j] != 0) BFS(i,j); } } printf("%d\n",Prim()); } return 0; }