标签:
题目链接:http://poj.org/problem?id=3026
题意:可以理解为给你一个地图上面有S和A的表示一个一个的点,#表示墙,所以需要我们用bfs来计算各点之间的距离;
b[i][j] = p;代表map[i][j]的位置的点的编号为p;
D[i][j] 代表编号为i和j的距离;
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> #include<algorithm> #include<queue> #include<iostream> using namespace std; #define N 105 #define INF 0xfffffff int dir[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} }; int D[N][N], n, m, vis[N], used[N][N],b[N][N], dist[N]; char map[N][N]; struct node { int x, y, step; } a[N]; void bfs(int s, int x, int y) { memset(used, 0, sizeof(used)); node p,q; queue<node>Q; p.x = x; p.y = y; p.step = 0; Q.push(p); used[x][y] = 1; while(Q.size()) { p = Q.front(); Q.pop(); if(map[p.x][p.y] >= ‘A‘ && map[p.x][p.y] <= ‘Z‘) D[s][ b[p.x][p.y] ] = p.step; for(int i=0; i<4; i++) { q.x = p.x + dir[i][0]; q.y = p.y + dir[i][1]; if(q.x<m && q.x>=0 && q.y>=0 && q.y<n && used[q.x][q.y]!=1 && map[q.x][q.y] != ‘#‘) { used[q.x][q.y] = 1; q.step = p.step + 1; Q.push(q); } } } } int Prim(int cnt) { int ans=0; vis[1] = 1; for(int i=1; i<=cnt; i++) dist[i] = D[1][i]; for(int i=1; i<=cnt; i++) { int Min = INF, index = -1; for(int j=1; j<=cnt; j++) if(vis[j]==0 && Min > dist[j]) { Min = dist[j]; index = j; } if(index==-1)break; ans += Min; vis[index] = 1; for(int j=1; j<=cnt; j++) { if(vis[j] == 0 && dist[j] > D[index][j]) dist[j] = D[index][j]; } } return ans; } int main() { int T, ans; scanf("%d", &T); while(T--) { memset(a, 0, sizeof(a)); memset(vis, 0, sizeof(vis)); memset(map, 0, sizeof(map)); for(int i=0; i<N; i++) { dist[i] = INF; for(int j=0; j<N; j++) D[i][j] = INF; D[i][i] = 0; } int cnt = 1; scanf("%d%d ", &n,&m); for(int i=0; i<m; i++) { gets(map[i]); for(int j=0; j<n; j++) { if(map[i][j] <= ‘Z‘ && map[i][j] >= ‘A‘) b[i][j] = cnt, cnt++; } } for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { if(map[i][j] <= ‘Z‘ && map[i][j] >= ‘A‘) bfs(b[i][j], i, j); } } ans = Prim(cnt-1); printf("%d\n", ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/zhengguiping--9876/p/4684325.html