解题思路,每个点都要标上号,用BFS搜索x,y(第i号顶点)到其余个顶点的距离,存了数组dis里面 就是prim算法的a[]数组
代码如下
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#define inf 0x3f3f3f3f
using namespace std;
struct node
{
int x, y;
int step;
}que[20000],q;
int n, m;
char map[160][160];
int w[160][160];
int book[160][160];
int dis[160][160];
int diss[160];
int vis[160];
int dx[] = {0,1,-1,0};
int dy[] = {1,0,0,-1};
void bfs(int x, int y)
{
int i;
memset(book,0,sizeof(book));
que[0].x = x;
que[0].y = y;
que[0].step = 0;
int head = 0;
int tail = 1;
book[x][y] = 1;
while(head < tail){
q = que[head];
head++;
if(map[q.x][q.y] == 'A'||map[q.x][q.y]=='S'){
dis[w[x][y]][w[q.x][q.y]] = dis[w[q.x][q.y]][w[x][y]] = q.step;
}
for(i = 0;i < 4;i++){
int xx = q.x+dx[i];
int yy = q.y+dy[i];
if(xx>=0&&xx<n&&yy>=0&&yy<m&&!book[xx][yy]&&map[xx][yy]!='#'){
que[tail].x = xx;
que[tail].y = yy;
que[tail].step = q.step+1;
book[xx][yy] = 1;
tail++;
}
}
}
}
void Prim(int n)
{
memset(vis,0,sizeof(vis));
int i, j, k;
for(i = 1;i <= n;i++){
diss[i] = dis[1][i];
}
int sum = 0;
int cnt = 1;
int Min;
vis[1] = 1;
while(cnt < n){
Min = inf;
for(i =1;i<= n;i++){
if(!vis[i] && diss[i] < Min){
Min = diss[i];
j = i;
}
}
sum += Min;
vis[j] =1;
cnt++;
for(k =1;k <= n;k++){
if(!vis[k]&&diss[k] > dis[j][k]){
diss[k] = dis[j][k];
}
}
}
printf("%d\n", sum);
}
int main()
{
int t;
scanf("%d", &t);
int ans;
int i, j;
while(t--){
memset(w,0,sizeof(w));
memset(dis,0,sizeof(dis));
memset(diss,0,sizeof(diss));
memset(map,0,sizeof(map));
ans = 0;
scanf("%d %d", &m, &n);
gets(map[0]);
for(i = 0;i < n;i++){
gets(map[i]);
}
for(i = 0;i < n;i++){
for(j = 0;j < m;j++){
if(map[i][j] == 'S'||map[i][j] =='A'){
w[i][j] = ++ans;
}
}
}
for(i = 0;i < n;i++){
for(j = 0;j < m;j++){
if(w[i][j] != 0){
bfs(i,j);
}
}
}
Prim(ans);
}
return 0;
}