您的位置:首页 > 其它

hdoj 1728(bfs+hash)(修复原版的bug)(重要)(调试的问题多就重新书写)

2012-03-04 15:17 246 查看
#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;

#define MAX 105

const int dir[4][2]={{0,-1},{1,0},{0,1},{-1,0}};

class Node
{
public:
int row,col,dir,cost;
};

int Row,Col;int startrow;int startcol;int endrow;int endcol;
const int lcost=1;const int rcost=1;
int k;//最大转弯次数
int result;//结果,

int mark[MAX][MAX][4];
char map[MAX][MAX];

queue<Node> q;

void check(Node next)
{
//如果出界的话
if(next.row<0||next.col<0||next.row>=Row||next.col>=Col)
return ;

//如果无法通过
if(map[next.row][next.col]=='*')
return;

//如果说得到一个
if(mark[next.row][next.col][next.dir]==-1||mark[next.row][next.col][next.dir]>next.cost)
{
mark[next.row][next.col][next.dir]=next.cost;
q.push(next);

}
}

int bfs()
{
Node now,next;

while(!q.empty())
{
now=q.front();q.pop();

//向前走一步
next.dir=now.dir;//方向不变
next.cost=now.cost;//费用不变
next.row=now.row+dir[next.dir][0];//位置改变
next.col=now.col+dir[next.dir][1];//位置改变
check(next);//检查

//向右转
next.dir=(now.dir+3)%4;//方向改变
next.cost=now.cost+rcost;//费用改变
next.row=now.row;//位置不变
next.col=now.col;//位置不变
check(next);//检查

//向左转
next.dir=(now.dir+1)%4;//方向改变
next.cost=now.cost+lcost;//费用改变
next.row=now.row;//位置不变
next.col=now.col;//位置不变
check(next);//检查
}
return 0;
}

int main()
{
//freopen("in.txt","r",stdin);
Node now;int i,j,k;
int casen;scanf("%d",&casen);

while(casen--)
{
//初始化

//清空队列
while(!q.empty())
q.pop();

//初始化hash
for(i=0;i<MAX;i++)
{
for(j=0;j<MAX;j++)
{
for(k=0;k<4;k++)
{
mark[i][j][k]=-1;
}
}
}

//初始化reuslt
result=100000;

//输入
scanf("%d %d",&Row,&Col);

for(i=0;i<Row;i++)
scanf("%s",map[i]);

scanf("%d",&k);
scanf("%d %d",&startcol,&startrow);//先输入的是列,让后才是行
scanf("%d %d",	&endcol,  &endrow);//先输入的是列,让后才是行

startcol--;startrow--;endcol--;endrow--;

now.row=startrow;now.col=startcol;now.cost=0;

//首先压入四个方向
for(i=0;i<4;i++)
{
now.dir=i;mark[now.row][now.col][i]=0;
q.push(now);
}

//处理
bfs();

//判断结果和输出
for(i=0;i<4;i++)
{
if(mark[endrow][endcol][i]==-1)
{
continue;
}
if(mark[endrow][endcol][i]<result)
{
result=mark[endrow][endcol][i];
}
}
if(result<=k)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
}
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐