Codeforces Round #327 & problem - 590C - C. Three States - BFS

C. Three States
time limit per test
5 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output

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.

Sample test(s)
input
4 5
11..2
#..22
#.323
.#333
output
2
input
1 5
1#2#3
output
-1


注意可能有公共路程


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#pragma comment(linker, "/STACK:1024000000,1024000000")

using namespace std;

#define ll long long
#define rep(x, y, z) for(int x=y;x<z;x++)
#define lson rt<<1, L, m
#define rson rt<<1|1, m, R
typedef pair<int, int> P;
#define mp(x, y) make_pair(x, y)
#define pb(x) push_back(x)
#define fi first
#define se second
const int maxn = 1e3 + 7;
const int INF = 0x3f3f3f3f;
const int tx[] = {1, 0, -1, 0}, ty[] = {0, 1, 0, -1};
int n, m;
char g[maxn][maxn];
int d[4][4];
int dis[4][maxn][maxn];
P find(char x){
	rep(i, 0, n) rep(j, 0, m) if(g[i][j] == x) return mp(i, j);
}
vector<P> ini(P p){
	vector<P> res;
	bool vis[maxn][maxn];
	memset(vis, 0, sizeof(vis));
	vis[p.fi][p.se] = 1;
	queue<P> q;
	q.push(p);
	while(!q.empty()){
		P t = q.front(); q.pop();
		res.pb(t);
		int x = t.fi, y = t.se;
		rep(i, 0, 4)
			if(x + tx[i] < n && x + tx[i] >= 0 && y + ty[i] < m && y + ty[i] >= 0 && g[x+tx[i]][y+ty[i]] == g[p.fi][p.se] && !vis[x+tx[i]][y+ty[i]]){
				q.push(mp(x + tx[i], y + ty[i]));
				vis[x+tx[i]][y+ty[i]] = 1;
			}
	}
	return res;
}
struct Node{
	int x, y, d;
	Node(){}
	Node(int a, int b, int c): x(a), y(b), d(c) {}
};
void work(int idd){
	vector<P> s = ini(find(idd));
	int sz = s.size();
	queue<Node> q;
	rep(i, 0, sz) q.push(Node(s[i].fi, s[i].se, 0));
	bool vis[maxn][maxn];
	memset(vis, 0, sizeof(vis));
	while(!q.empty()){
		Node t = q.front(); q.pop();
		int x = t.x, y = t.y;
		rep(i, 0, 4)
			if(x + tx[i] < n && x + tx[i] >= 0 && y + ty[i] < m && y + ty[i] >= 0 && g[x+tx[i]][y+ty[i]] != '#' && !vis[x+tx[i]][y+ty[i]]){
				vis[x+tx[i]][y+ty[i]] = 1;
				if(g[x+tx[i]][y+ty[i]] == '.') {
					q.push(Node(x+tx[i], y+ty[i], t.d+1));
					dis[idd-'0'][x+tx[i]][y+ty[i]] = t.d;
				}
				else if(g[x+tx[i]][y+ty[i]] != idd) d[g[x+tx[i]][y+ty[i]]-'0'][idd-'0'] = d[idd-'0'][g[x+tx[i]][y+ty[i]]-'0'] = min(d[g[x+tx[i]][y+ty[i]]-'0'][idd-'0'], t.d);
			}
	}
}
ll ans = INF;
bool solve(){
	rep(i, 1, 4) rep(j, 1, 4) rep(k, 1, 4){
		if(i == j || i == k || j == k) continue;
		if(d[i][j] != INF && d[j][k] != INF) ans = min(ans, (ll)d[i][j] + d[j][k]);
	}
	if(ans == INF) return false;
	return true;
}
int main(){
#ifdef ac
	freopen("in.txt","r",stdin);
#endif
	//freopen("out.txt","w",stdout);
	memset(d, INF, sizeof(d));
	memset(dis, INF, sizeof(dis));
    scanf("%d%d", &n, &m);
	rep(i, 0, n) scanf("%s", g[i]);
	rep(i, 1, 4) work(i+'0');
	if(!solve()){
		printf("-1\n");
		return 0;
	}
	else {
		rep(i, 0, n) rep(j, 0, m) ans = min(ans, (ll)dis[1][i][j]+dis[2][i][j]+dis[3][i][j]+1);
		printf("%lld\n", ans);
	}
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值