[BFS+prime]Borg Maze

本文介绍了一种算法,用于解决迷宫中最短路径的问题,特别是涉及到多个目标点且需要考虑障碍物的情况。该算法首先通过广度优先搜索(BFS)计算任意两点间的最短距离,然后应用Prim算法来找出连接所有目标点的最小生成树,从而得到最短路径的总长度。
摘要由CSDN通过智能技术生成

Time Limit:1000MS    Memory Limit:65536KB    64bit IO Format:%lld & %llu

Description

The Borg is an immensely powerful race of enhanced humanoids from the delta quadrant of the galaxy. The Borg collective is the term used to describe the group consciousness of the Borg civilization. Each Borg individual is linked to the collective by a sophisticated subspace network that insures each member is given constant supervision and guidance.

Your task is to help the Borg (yes, really) by developing a program which helps the Borg to estimate the minimal cost of scanning a maze for the assimilation of aliens hiding in the maze, by moving in north, west, east, and south steps. The tricky thing is that the beginning of the search is conducted by a large group of over 100 individuals. Whenever an alien is assimilated, or at the beginning of the search, the group may split in two or more groups (but their consciousness is still collective.). The cost of searching a maze is definied as the total distance covered by all the groups involved in the search together. That is, if the original group walks five steps, then splits into two groups each walking three steps, the total distance is 11=5+3+3.

Input

On the first line of input there is one integer, N <= 50, giving the number of test cases in the input. Each test case starts with a line containg two integers x, y such that 1 <= x,y <= 50. After this, y lines follow, each which x characters. For each character, a space `` '' stands for an open space, a hash mark ``#'' stands for an obstructing wall, the capital letter ``A'' stand for an alien, and the capital letter ``S'' stands for the start of the search. The perimeter of the maze is always closed, i.e., there is no way to get out from the coordinate of the ``S''. At most 100 aliens are present in the maze, and everyone is reachable.

Output

For every test case, output one line containing the minimal cost of a succesful search of the maze leaving no aliens alive.

Sample Input

2
6 5
##### 
#A#A##
# # A#
#S  ##
##### 
7 7
#####  
#AAA###
#    A#
# S ###
#     #
#AAA###
#####  

Sample Output

8
11



大致题意:

在一个y行 x列的迷宫中,有可行走的通路空格’ ‘,不可行走的墙’#’,还有两种英文字母A和S,现在从S出发,要求用最短的路径L连接所有字母,输出这条路径L的总长度。

 

一格的长度为1,而且移动的方法只有上、下、左、右,

所以在无任何墙的情况下(但“墙#”是必须考虑的,这里只是为了说明)

任意两个字母之间的距离就是直接把 横坐标之差 加上 纵坐标之差

注意的是,可行的路为 字母 和 空格

          不可行的路为 # 和 矩阵范围之外

 

根据题意的“分离”规则,重复走过的路不再计算

因此当使用prim算法求L的长度时,根据算法的特征恰好不用考虑这个问题(源点合并很好地解决了这个问题),L就是最少生成树的总权值W

 

由于使用prim算法求在最小生成树,因此无论哪个点做起点都是一样的,(通常选取第一个点),因此起点不是S也没有关系

所以所有的A和S都可以一视同仁,看成一模一样的顶点就可以了

 

最后要注意的就是 字符的输入

cin不读入空字符(包括 空格,换行等)

gets读入空格,但不读入换行符)

 

剩下的问题关键就是处理 任意两字母间的最短距离,由于存在了“墙#” ,这个距离不可能单纯地利用坐标加减去计算,必须额外考虑,推荐用BFS(广搜、宽搜),这是本题的唯一难点,因为prim根本直接套用就可以了

 

任意两字母间的最短距离 时不能直接用BFS求,

1、必须先把矩阵中每一个允许通行的格看做一个结点(就是在矩阵内所有非#的格都作为图M的一个顶点),对每一个结点i,分别用BFS求出它到其他所有结点的权值(包括其本身,为0),构造结点图M;

2、然后再加一个判断条件,从图M中抽取以字母为顶点的图,进而构造字母图N

这个判定条件就是当结点图M中的某点j为字母时,把i到j的权值再复制(不是抽离)出来,记录到字母图N的邻接矩阵中

3、剩下的就是对字母图N求最小生成树了

# include <iostream>
# include <cstdio>
# include <cstring>
# include <queue>
using namespace std;

const int N = 105;
const int INF = INT_MAX;

struct st
{
    int x, y, step;
}tmp, w;

int map[N][N];      //用来记录最原始的图形
bool vis[N][N];
bool vis1[N];       //记录每一个点是否被访问过   prime中使用
int dist[N][N];     //记录每个点的距离 prime中使用
int dirt[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int lowcast[N];
int t, n, m;
int nodenum;        //记录点的个数

bool check(int x, int y)
{
    return x>=0 && x<n && y>=0 && y<m && map[x][y]!=-1;
}


void BFS(int u)     //u表示的是每个顶点的编号 不一定从1开始  但是每个都会遍历
{
    memset(vis, false, sizeof(vis));
    vis[w.x][w.y] = true;           //标记
    queue<st> q;
    q.push(w);
    while ( !q.empty() )
    {
        w = q.front();
        q.pop();
        if (map[w.x][w.y] > 0)      //map[w.x][w.y]中存放的是找到的其他的点
        {
            dist[u][map[w.x][w.y]] = w.step;
        }
        for (int i=0; i<4; i++)
        {
            tmp.x = w.x + dirt[i][0];
            tmp.y = w.y + dirt[i][1];
            tmp.step = w.step + 1;
            if (check(tmp.x, tmp.y) && !vis[tmp.x][tmp.y])
            {
                vis[tmp.x][tmp.y] = true;
                q.push(tmp);
            }
        }
    }
}

void prime()
{
    memset(vis1, false, sizeof(vis1));
    int sum = 0;
    int k;
    int min = INF;
    vis1[1] = true;
    for (int i=1; i<=nodenum; i++)
    {
        lowcast[i] = dist[1][i];        //注意:不能写成map[][]
    }
    for (int i=1; i<=nodenum; i++)
    {
        min = INF;
        for (int j=1; j<=nodenum; j++)
        {
            if (!vis1[j] && lowcast[j]<min)
            {
                min = lowcast[k = j];
            }
        }

        if (min == INF)
        {
            break;
        }

        sum += min;
        vis1[k] = true;
        for (int j=1; j<=nodenum; j++)
        {
            if (!vis1[j] && lowcast[j]>dist[k][j])
            {
                lowcast[j] = dist[k][j];
            }
        }
    }

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

int main()
{
    scanf("%d", &t);
    char temp[N];
    while (t--)
    {
        nodenum = 0;
        scanf("%d %d", &m, &n);
        gets(temp);
        for (int i=0; i<n; i++)
        {
            gets(temp);
            for (int j=0; j<m; j++)
            {
                if (temp[j] == 'S' || temp[j] == 'A')
                {
                    map[i][j] = ++nodenum;
                }
                else if (temp[j] == ' ')
                {
                    map[i][j] = 0;
                }
                else
                {
                    map[i][j] = -1;
                }
            }
        }

        for (int i=0; i<n; i++)
        {
            for (int j=0; j<m; j++)
            {
                if (map[i][j] > 0)      //每个点进行一次BFS  构造出dist[][]
                {
                    w.x = i;
                    w.y = j;
                    w.step = 0;
                    BFS( map[i][j] );
                }
            }
        }

        prime();
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值