hdu 2822 Dogs
2013-08-11 12:20
351 查看
http://acm.hdu.edu.cn/showproblem.php?pid=2822
分析:遇到'.'(挖隧道)的时候才需要步数加1,'X'是一个整体,利用优先队列选择步数最小的开始广搜
不过这样效率比较低,可以用双搜加快效率
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int NM=1005;
int a[4][2]={-1,0,1,0,0,1,0,-1};
int vis[NM][NM],n,m,x1,y1,x2,y2;
char str[NM][NM];
struct Dog{
int x,y,ans;
};
bool operator < (struct Dog A,struct Dog B)
{
if(A.ans>B.ans) return 1;
else return 0;
}
void BFS()
{
priority_queue<Dog>pq1;
Dog t,p;
int i,j;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
vis[i][j]=0;
t.x=x1,t.y=y1;
t.ans=0;
vis[t.x][t.y]=1;
pq1.push(t);
while(!pq1.empty())
{
t=pq1.top();pq1.pop();
if(t.x==x2&&t.y==y2)
{
printf("%d\n",t.ans);
return;
}
for(i=0;i<4;i++)
{
p.x=t.x+a[i][0],p.y=t.y+a[i][1];
p.ans=t.ans;
if(p.x>=0&&p.x<n&&p.y>=0&&p.y<m&&!vis[p.x][p.y])
{
if(str[p.x][p.y]=='.')
p.ans++;
vis[p.x][p.y]=1;
pq1.push(p);
}
}
}
}
int main()
{
int i;
while(scanf("%d%d",&n,&m)&&(n||m))
{
for(i=0;i<n;i++)
scanf("%s",str[i]);
scanf("%d%d",&x1,&y1);
scanf("%d%d",&x2,&y2);
x1-=1,y1-=1;
x2-=1,y2-=1;
BFS();
}
return 0;
}
分析:遇到'.'(挖隧道)的时候才需要步数加1,'X'是一个整体,利用优先队列选择步数最小的开始广搜
不过这样效率比较低,可以用双搜加快效率
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int NM=1005;
int a[4][2]={-1,0,1,0,0,1,0,-1};
int vis[NM][NM],n,m,x1,y1,x2,y2;
char str[NM][NM];
struct Dog{
int x,y,ans;
};
bool operator < (struct Dog A,struct Dog B)
{
if(A.ans>B.ans) return 1;
else return 0;
}
void BFS()
{
priority_queue<Dog>pq1;
Dog t,p;
int i,j;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
vis[i][j]=0;
t.x=x1,t.y=y1;
t.ans=0;
vis[t.x][t.y]=1;
pq1.push(t);
while(!pq1.empty())
{
t=pq1.top();pq1.pop();
if(t.x==x2&&t.y==y2)
{
printf("%d\n",t.ans);
return;
}
for(i=0;i<4;i++)
{
p.x=t.x+a[i][0],p.y=t.y+a[i][1];
p.ans=t.ans;
if(p.x>=0&&p.x<n&&p.y>=0&&p.y<m&&!vis[p.x][p.y])
{
if(str[p.x][p.y]=='.')
p.ans++;
vis[p.x][p.y]=1;
pq1.push(p);
}
}
}
}
int main()
{
int i;
while(scanf("%d%d",&n,&m)&&(n||m))
{
for(i=0;i<n;i++)
scanf("%s",str[i]);
scanf("%d%d",&x1,&y1);
scanf("%d%d",&x2,&y2);
x1-=1,y1-=1;
x2-=1,y2-=1;
BFS();
}
return 0;
}
相关文章推荐
- hdu 2822 Dogs(优先队列)
- hdu 2822 Dogs
- hdu 2822 Dogs(bfs+优先队列)
- hdu 2822 Dogs
- hdu 2822 Dogs (优先队列 + BFS)
- hdu - 2822 Dogs (优先队列+bfs)
- hdu 2822 Dogs
- HDU 2822 Dogs
- HDU - 2822 Dogs(广搜+优先队列)
- 广搜+优先队列 HDU-2822 D - Dogs
- hdu 2822 Dogs(搜索)
- HDU 2822 Dogs
- HDU 2822 Dogs【两次bfs】
- HDU 2822 Dogs(优先队列)
- HDU - 2822 Dogs (优先队列+bfs)
- hdu 2822 Dogs 优先队列
- HDU 2822 Dogs【两次bfs】
- hdu 2822 Dogs【优先队列+Bfs】
- hdu 2822 Dogs(优先队列)
- hdu 2822 Dogs(BFS + 优先队列)