您的位置:首页 > 大数据 > 人工智能

2012 Multi-University Training Contest 1 Saving Princess claire(广搜)

2012-07-21 20:57 295 查看
广搜求最距离。

一个细节:由于每个'P'之间是相通的,所以当搜到第一个'P’时,紧接着就应该把其他'P'点加入到队列中。

<span style="font-size:18px;">#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
#define maxn 2000
int row,col,cost;
char map[maxn][maxn];
bool visit[maxn][maxn];
struct node{
int x;
int y;
int step;
};
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
bool bian(int x,int y)
{
if(x>=0 && x<row && y>=0 && y<col)
return 1;
return 0;
}
int number;
int ex,ey;
int Px[5000],Py[5000];
int bfs(int x,int y)
{
int k,i,j,tx,ty;
node from,to,head,tp,temp;
queue<node>Q;
while(!Q.empty())
Q.pop();
memset(visit,false,sizeof(visit));
from.x=x;
from.y=y;
from.step=0;
Q.push(from);
visit[x][y]=true;
while(!Q.empty())
{
head=Q.front();
Q.pop();
for(i=0;i<4;i++)
{
temp.x=head.x+dx[i];
temp.y=head.y+dy[i];

if(bian(temp.x,temp.y) && !visit[temp.x][temp.y] && map[temp.x][temp.y]!='#')
{
if(map[temp.x][temp.y]=='C')
{
temp.step=head.step;
return temp.step;
}
else if(map[temp.x][temp.y]=='P')
{
for(j=0;j<number;j++)
{
temp.x=Px[j];
temp.y=Py[j];
temp.step=head.step;
Q.push(temp);
visit[temp.x][temp.y]=true;
}
}
else if(map[temp.x][temp.y]=='*')
{
temp.step=head.step+1;
Q.push(temp);
visit[temp.x][temp.y]=true;
}
}

}
}
return -1;
}
int main()
{
int i,j,x,y;
while(scanf("%d%d%d",&row,&col,&cost)==3)
{
for(i=0;i<row;i++)
scanf("%s",&map[i]);
number=0;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
{
if(map[i][j]=='Y')
{
x=i;
y=j;
}
else if(map[i][j]=='C')
{
ex=i;
ey=j;
}
else if(map[i][j]=='P')
{
Px[number]=i;
Py[number]=j;
number++;
}
}
int op=bfs(x,y);
if(op!=-1)
printf("%d\n",op*cost);
else
printf("Damn teoy!\n");
}
}
</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: