poj 3026 Borg Maze

http://poj.org/problem?id=3026

题意:在一个y行 x列的迷宫中,有可行走的通路空格’ ‘,不可行走的墙’#’,还有两种英文字母A和S,现在从S出发,要求用最短的路径L连接所有字母,输出这条路径L的总长度;

思路:用bfs找出每两个点之间的距离,然后用prim求出最小生成树;思路是参考网上的;

代码:

View Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
using namespace std;
#define inf 2501
char map[51][51] = {'0'};
int node[51][51] = {0};
int col = 0;
int row = 0;
int num = 0;
int edge[102][102] = {0};
int dist[102][102] = {0};
struct node
{
int row;
int col;
}mov[4]={{0,-1},{0,1},{-1,0},{1,0}};
void bfs(int i,int j)
{
bool visit[51][51] = {0};
queue<int>x;
queue<int>y;
//memset(visit,0,sizeof(visit));
x.push(i);
y.push(j);
int tem = node[i][j];
//printf("%d hhhh\n",tem);
memset(dist,0,sizeof(dist));
visit[i][j] = 1;
while(!x.empty())
{

int x1 = x.front();
int y1 = y.front();

x.pop();
y.pop();
if(node[x1][y1])
edge[tem][node[x1][y1]] = dist[x1][y1];
//printf("%d \n",edge[node[i][j]][node[x1][y1]]);
for(int k = 0;k < 4; ++k)
{
int mx = x1 + mov[k].row;
int my = y1 + mov[k].col;
if(mx >= 1&&mx <= row&&my >= 1&&my <= col&&!visit[mx][my]&&map[mx][my] != '#')
{
x.push(mx);
y.push(my);
visit[mx][my] = 1;
dist[mx][my] = dist[x1][y1] + 1;
//printf("%d \n",dist[mx][my]);
}

}
}
//printf("JJJJJdd\n");
}
void prim()
{
int di[102] = {0};
bool vis[102] = {0};
// printf("JFDk");
for(int i = 1;i <= num; ++i)
{
di[i] = edge[1][i];
vis[i] = 0;
}
int ans = 0;
vis[1] = 1;
for(int i =1;i < num; ++i)
{
int min = inf;
int p = 0;
for(int j = 2;j <= num; ++j)
if(!vis[j] && di[j] < min)
{
min = di[j];
p = j;
}
vis[p] = 1;
ans = ans + min;
//printf("%d %d \n",min,p);
for(int j = 1;j <= num; ++j)
if(!vis[j] && di[j] > edge[p][j])
di[j] = edge[p][j];
}
printf("%d\n",ans);
}
int main()
{
int test = 0;
cin>>test;
while(test--)
{
memset(node,0,sizeof(node));
num = 0;
cin>>col>>row;
char temp[51] = {0};
gets(temp);
for(int i = 1;i <= row; ++i)
{
gets(map[i]);
for(int j = 1;j <= col;++j)
if(map[i][j] == 'A' || map[i][j] == 'S')
node[i][j] = ++num;
}
for(int i = 1;i <= row; ++i)
for(int j = 1;j <= col; ++j)
if(node[i][j])
bfs(i,j);
//for(int i = 1;i <= num;++i)
//for(int j = 1;j <= num; ++j)
//printf("%d %d %d\n",edge[i][j],i,j);
prim();
}
return 0;
}



posted @ 2012-03-16 15:03  LT-blogs  阅读(200)  评论(0编辑  收藏  举报