POJ - 3026 Borg Maze
https://vjudge.net/problem/POJ-3026

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int N=60,M=120;
int x,y,cnt,ans;
char str[N][N];
int e[M][M],g[M][M],dis[M];
bool bt[N][N],bk[M];
struct node{
int x,y,step;
}t1,t2;
int dt[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
void bfs(int sx,int sy)
{
queue<node> q;
while(!q.empty()) q.pop();
memset(bt,false ,sizeof bt);
t1.x=sx;
t1.y=sy;
t1.step=0;
bt[sx][sy]=true;
q.push(t1);
while(q.size())
{
t1=q.front();
q.pop();
if(e[t1.x][t1.y]) //因为每个点都分配了唯一值,对于每次的bfs,sx,sy都是固定的,
g[e[sx][sy]][e[t1.x][t1.y]]=t1.step; //因此每次扫到e[t1.x][t1.y]存在,那么就更新一次
//e[t1.x][t1.y] 这个点先是在下方的循环中被入列,在这个才能扫到
for(int i=0;i<4;i++)
{
int dx=t1.x+dt[i][0],dy=t1.y+dt[i][1];
if(dx>=1 && dx<=x && dy>=1 && dy<=y && !bt[dx][dy] && str[dx][dy]!='#')
{
bt[dx][dy]=true;
t2.x=dx;
t2.y=dy;
t2.step=t1.step+1;
q.push(t2);
}
}
}
}
void prim()
{
memset(bk,false,sizeof bk);
memset(dis,0x3f,sizeof dis);
ans=0;
for(int i=0;i<cnt-1;i++)
{
int t=-1;
for(int j=1;j<=cnt-1;j++)
{
if(!bk[j] && (t==-1 || dis[t]>dis[j]))
t=j;
}
bk[t]=true;
if(i) ans+=dis[t];
for(int j=1;j<=cnt-1;j++)
if(dis[j]>g[t][j])
dis[j]=g[t][j];
}
return;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d %d",&y,&x);
gets(str[0]);
memset(e,0,sizeof e);
memset(g,0x3f,sizeof g);
cnt=1;
for(int i=1;i<=x;i++)
{
gets(str[i]+1);
for(int j=1;j<=y;j++)
if(str[i][j]=='S' || str[i][j]=='A')
e[i][j]=cnt++;
}
for(int i=1;i<=x;i++)
for(int j=1;j<=y;j++)
if(e[i][j])
bfs(i,j);
// for(int i=1;i<=10;i++)
// {
// for(int j=1;j<=10;j++)
// cout<<g[i][j];
// cout<<endl;
// }
prim();
printf("%d\n",ans);
}
return 0;
}
本文来自博客园,作者:斯文~,转载请注明原文链接:https://www.cnblogs.com/zhiweb/p/15483302.html

浙公网安备 33010602011771号