#include<iostream>
#include<vector>
#include<algorithm>
#include<utility>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<map>
#include<string>
#include<queue>
#define MAXAMOUNT 110
using namespace std;
char Map[100][100];
int x, y;
int n;
int ans;
int start[2];
int pointcnt;
typedef struct node
{
int s[2];//起点终点在图中的坐标
int e[2];
int p;
}node;
//重载
bool operator <(node a, node b)
{
return a.p > b.p;
}
typedef struct cell
{
int x, y;
int step;
}cell;
int vis[MAXAMOUNT][MAXAMOUNT] = { 0 };
bool book[MAXAMOUNT][MAXAMOUNT];
int opx[4] = { 1,-1,0,0 };
int opy[4] = { 0,0,1,-1 };
void prim(int s[2])
{
node nn;
vis[s[0]][s[1]] = 1;
int all = 1;
ans = 0;
priority_queue<node> qq;
while (all < pointcnt)
{
//通过bfs放进去边
memset(book, 0, sizeof(book));
int c = pointcnt - all;//剩余的没有放入树中的点的个数
queue<cell> Q;
cell cc;
cc.step = 0;
cc.x = s[0];
cc.y = s[1];
book[cc.x][cc.y] = 1;
Q.push(cc);
while (!Q.empty() && c)//还有非vis的元素没有访问就继续搜索
{
cell tn = Q.front();
Q.pop();
int xx = tn.x;
int yy = tn.y;
if ((Map[xx][yy] == 'S' || Map[xx][yy] == 'A') && !vis[xx][yy])
{
c--;
nn.s[0] = s[0];
nn.e[0] = xx;
nn.s[1] = s[1];
nn.e[1] = yy;
nn.p = tn.step;
qq.push(nn);
}
cell nc;
for (int i = 0;i < 4;i++)
{
nc.x = tn.x + opx[i];
nc.y = tn.y + opy[i];
if (Map[nc.x][nc.y] != '#' && !book[nc.x][nc.y])
{
nc.step = tn.step + 1;
book[nc.x][nc.y] = 1;
Q.push(nc);
}
}
}
//
while (!qq.empty()&&vis[qq.top().e[0]][qq.top().e[1]])
qq.pop();//没用的不要
nn = qq.top();
qq.pop();
s[0] = nn.e[0];
s[1] = nn.e[1];
ans += nn.p;
vis[s[0]][s[1]] = 1;
all++;
}//while
}//prim
int main()
{
int t;
scanf("%d", &t);
getchar();
while (t--)
{
memset(vis, 0, sizeof(vis));
pointcnt = 0;
//创建图的是信息
char in[500];
cin.getline(in, 499);
sscanf(in,"%d %d", &x, &y);
for (int i = 0;i < y;i++)
{
cin.getline(Map[i], 100);
int len = strlen(Map[i]);
for (int j = 0;j < len;j++)
{
if (Map[i][j] == 'S')
{
start[0] = i;
start[1] = j;
pointcnt++;
}
if (Map[i][j] == 'A')
{
pointcnt++;
}
}
}
ans = 0;
prim(start);
printf("%d\n", ans);
//cout << "The highest possible quality is 1/" << ans << "." << endl;
}//while
return 0;
}
POJ 3026 BFS+PRIM 地图上迷宫最小生成树
最新推荐文章于 2021-06-24 20:49:39 发布