J - Borg Maze - poj 3026(BFS+prim)

在一个迷宫里面需要把一些字母。也就是 ‘A’ 和 ‘B’连接起来,求出来最短的连接方式需要多长,也就是最小生成树,地图需要预处理一下,用BFS先求出来两点间的最短距离,
**********************************************************************************
#include<algorithm>
#include<stdio.h>
#include< string.h>
#include<queue>
using  namespace std;

const  int maxn =  105;
const  int oo =  0xfffffff;

int  dir[ 4][ 2] = { { 1, 0},{ 0, 1},{- 1, 0},{ 0,- 1} };
char G[maxn][maxn];           // 保存地图
int  D[maxn][maxn];           // 记录两点间的距离
int  use[maxn][maxn];         // 标记地图
int  Index[maxn][maxn];       // 记录‘A’或者‘B’的编号
struct node{ int x, y, step;};

void BFS( int k,  int M, int N,  int x,  int y)
{
    queue<node> Q;
    node s;
    s.x = x, s.y = y, s.step =  0;
    use[s.x][s.y] = k; Q.push(s);

     while(Q.size())
    {
        s = Q.front();Q.pop();
         if(G[s.x][s.y]>= ' A ' && G[s.x][s.y] <= ' Z ')
            D[k][ Index[s.x][s.y] ] = s.step;

         for( int i= 0; i< 4; i++)
        {
            node q = s;
            q.x += dir[i][ 0], q.y += dir[i][ 1];

             if(q.x>= 0&&q.x<M && q.y>= 0&&q.y<N && G[q.x][q.y]!= ' # ' && use[q.x][q.y]!=k)
            {
                use[q.x][q.y] = k;
                q.step +=  1;
                Q.push(q);
            }
        }
    }
}
int  Prim( int N)             // 这里面的N代表编号最多到N
{
     int i, dist[maxn], vis[maxn]={ 01};
     int ans =  0, T=N- 1;

     for(i= 1; i<=N; i++)
        dist[i] = D[ 1][i];

     while(T--)
    {
         int k= 1, mini = oo;

         for(i= 1; i<=N; i++)
        {
             if(!vis[i] && mini > dist[i])
                mini = dist[i], k=i;
        }
        ans += mini;
        vis[k] =  true;

         for(i= 1; i<=N; i++)
             if(!vis[i])dist[i] = min(dist[i], D[k][i]);
    }

     return ans;
}

int main()
{
     int T;

    scanf( " %d ", &T);

     while(T--)
    {
         int i, j, M, N, t= 1;

        scanf( " %d%d  ", &N, &M);

         for(i= 0; i<M; i++)
        {
            gets(G[i]);
             for(j= 0; j<N; j++)
            {
                 if(G[i][j]>= ' A ' && G[i][j]<= ' Z ')
                    Index[i][j] = t++;
                use[i][j] =  0;
            }
        }

         for(i= 0; i<M; i++)
         for(j= 0; j<=N; j++)
        {
             if(G[i][j]>= ' A ' && G[i][j]<= ' Z ')
                BFS(Index[i][j], M, N, i, j);
        }

         int ans = Prim(t- 1);

        printf( " %d\n ", ans);
    }

     return  0;
}

你可能感兴趣的:(Prim)