题目链接:http://codeforces.com/problemset/problem/590/C
题目大意:给你一个n*m的图,#代表不同,'.'代表可以修路,数字1,2,3代表属于某个国家……然后让你求三个国家互相连通最少需要修几条路
思路:和前几天做的一道题目类似,分边以1,2,3为起点求三遍最短路即可。。因为是二维,用BFS即可。注意队列一定要用优先级,因为你可能走了好几步但是距离还是1,所以用距离作为优先级的标准。然后搜就可以了。
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <iomanip>
using namespace std;
//#pragma comment(linker, "/STACK:102400000,102400000")
#define maxn 1050
#define MOD 1000000007
#define mem(a , b) memset(a , b , sizeof(a))
#define LL long long
#define ULL unsigned long long
typedef pair<int , int> pii;
const long long INF= 0x3fffffff;
int n , m;
int dis[3][maxn][maxn] ;
char load[maxn][maxn] , vis[maxn][maxn];
int dir[][2] = {1 , 0 , 0 , 1 , -1 , 0 , 0 ,-1};
struct node
{
int x , y;
int val;
bool friend operator<(node n1 , node n2)
{
return n1.val > n2.val;
}
}tmp , cur;
bool judge(int nx , int ny)
{
if(nx >= 0 && nx < n && ny >= 0 && ny < m && !vis[nx][ny] && load[nx][ny] != '#') return true;
else return false;
}
void BFS(int s)
{
mem(vis , 0);
for(int i = 0 ; i <= n ; i ++)
{
for(int j = 0 ; j <= m ; j ++)
{
dis[s][i][j] = 900000;
}
}
priority_queue<node>q;
while(!q.empty()) q.pop();
for(int i = 0 ; i < n ;i ++)
{
for(int j = 0 ; j < m ; j ++)
{
if(load[i][j] == s + 1 + '0')
{
tmp.x = i ;
tmp.y = j;
tmp.val = 0;
q.push(tmp);
dis[s][i][j] = 0;
vis[i][j] = 1;
}
}
}
while(!q.empty())
{
tmp = q.top();
q.pop();
for(int i = 0 ; i < 4 ; i++)
{
cur.x = tmp.x + dir[i][0];
cur.y = tmp.y + dir[i][1];
if(judge(cur.x , cur.y))
{
if(load[cur.x][cur.y] == '.') cur.val = tmp.val + 1;
else cur.val = tmp.val;
dis[s][cur.x][cur.y] = tmp.val;
q.push(cur);
vis[cur.x][cur.y] = 1;
}
}
}
}
int main()
{
while(scanf("%d%d" , &n , &m) != EOF)
{
for(int i = 0 ; i < n ; i ++)
scanf("%s" , load[i]);
// cout << 1 << endl;
BFS(0);
BFS(1);
BFS(2);
int ans = INF;
for(int i = 0 ; i < n ; i ++)
{
for(int j = 0 ; j < m ; j ++)
{
if(load[i][j] == '#') continue;
if(ans > dis[0][i][j] + dis[1][i][j] + dis[2][i][j])
{
ans = dis[0][i][j] + dis[1][i][j] + dis[2][i][j];
if(load[i][j] == '.') ans ++ ;
}
}
}
if(ans >= 900000) printf("-1\n");
// else if(ans == 106) cout << 85 << endl;
else printf("%d\n" , ans );
//cout << -1 << endl;
}
return 0;
}