Codeforces round 591E Three States (思维优化BFS)

全球经济危机逼近,Berman、Berance和Bertaly三国结盟,允许居民自由穿越彼此领土,并需建设一条连接三国的公路。任务是用最少的预算在地图上建造道路,确保能从任一州的任一位置到达其他任一州。地图由n行m列组成,包含三个州、可建路区域和不可建路区域。目标是构建一条允许在可通行区域内上下左右移动的道路,初始时每个州内任意位置都能到达其他州。输入包含地图尺寸和详细描述,输出为所需的最小道路建设数量,若无法实现则输出-1。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.

Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.

Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.

It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.

Input

The first line of the input contains the dimensions of the map n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns respectively.

Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.

Output

Print a single integer — the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.

Examples

Input

4 5
11..2
#..22
#.323
.#333

Output

2

Input

1 5
1#2#3

Output

-1
#include<iostream>
#include<algorithm>
#include<string>
#include<map>//int dx[4]={0,0,-1,1};int dy[4]={-1,1,0,0};
#include<queue>//int gcd(int a,int b){return b?gcd(b,a%b):a;}
#include<vector>
#include<cmath>
#include<stack>
#include<string.h>
#include<stdlib.h>
#include<cstdio>
#define mod 1e9+7
#define ll long long
#define maxn 1005
#define MAX 500005
#define ms memset
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000") ///在c++中是防止暴栈用的

int dist[4][maxn][maxn];
struct node
{
    int x,y,dis;
    node(int xx=0,int yy=0)
    {
        dis=0;
        x=xx;
        y=yy;
    }
    bool operator<(const node& y) const
    {
        return dis>y.dis;
    }
};
/*
题目大意:在一张地图中,
给定三块连通域分别用1,2,3标记。
问如何建路使三块领域互相连通,
并求其最少的建路数。

bfs的对象是:从领域到每个点的最短路。
然后枚举所有点即可,记得如果改点为空白
则答案减2,因为路径重复叠加了两次。
详情见代码内容。

另外读题要仔细,题目中说是一条路。。。。。
mmp想多了。。
所以枚举所有点更新答案即可
*/

int dx[]= {0,0,1,-1};
int dy[]= {1,-1,0,0};
char c[maxn];
int n,m,mp[maxn][maxn];

void Bfs(int d)
{
    priority_queue<node> pq;///优先队列
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
    {
        if(mp[i][j]==d)
        {
            dist[d][i][j] = 0;
            pq.push( node(i,j) );
        }
    }

    while( !pq.empty() )
    {
        node nw,ft=pq.top();
        pq.pop();

        for(int i=0;i<4;i++)
        {
            int tx=ft.x+dx[i];
            int ty=ft.y+dy[i];

            if( tx <= 0 || tx>n || ty<=0 || ty>m) continue;
            if( mp[tx][ty] == -1 ) continue;

            if( mp[tx][ty] == 0 ) nw.dis=ft.dis+1;
            else nw.dis=ft.dis;

            if( dist[d][tx][ty] > nw.dis || dist[d][tx][ty]==-1)///-1代表无穷大
            {
                nw.x=tx , nw.y=ty;
                pq.push(nw);
                dist[ d ][ tx ][ ty ] = nw.dis;
            }
        }
    }
}

int main()
{
    scanf("%d%d",&n,&m);

    for(int i=1;i<=n;i++)
    {
        scanf("%s",c+1);
        for(int j=1;j<=m;j++)
        {
            if(c[j]=='.') mp[i][j]=0;
            else if(c[j]=='#') mp[i][j]=-1;
            else mp[i][j]=c[j]-'0';
        }
    }

    memset(dist,0xff,sizeof(dist));
    Bfs(1)  , Bfs(2) , Bfs(3);

    int ans=-1;///cout<<ans<<endl;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
    {
        int flag=0,op=0;
        for(int d=1;d<=3;d++)
        {
            if(dist[d][i][j]==-1)
            {
                flag=1;
                break;
            }
            op += dist[d][i][j];
        }
        if(flag) continue;
        if(mp[i][j]==0) op -= 2;
        if( ans==-1 || op < ans ) ans=op;
    }

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值