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

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;
}

猜你喜欢

转载自blog.csdn.net/qq_37451344/article/details/81175668