图论之搜索部分解题思路

HDU1728:http://acm.hdu.edu.cn/showproblem.php?pid=1728

该题不难,简单的BFS,其复杂的地方就是要找出其最小的转弯次数

#include<iostream>
#include<queue>
using namespace std;
int Sx,Sy,Ex,Ey,T;
int visit[101][101];
int n,m;
char Map[101][101];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct Node
{
	int x;
	int y;
	int step; //转弯次数
	int dir;

}; 
void BFS(int x,int y)
{
  queue<Node> Q;
  Node New;
  New.x=x;
  New.y=y;
  New.step=0;
  New.dir=-1;  //构建第一个节点信息
  visit[x][y]=0;  //无转弯
  Q.push(New);
  while(!Q.empty())
  {
	  New=Q.front(); 
	  Q.pop();	  
	  int u;
	  for(u=0;u<4;u++)
	  {
		  Node top=New;
		  top.x+=dir[u][0];
		  top.y+=dir[u][1];
		  if(top.x<1||top.x>n||top.y<1||top.y>m||Map[top.x][top.y]=='*') //越界、越到墙
		  continue;
			  if(top.dir!=u&&top.dir!=-1) //转弯判定,可推演
				  top.step++; 
			  if(top.step>T) //超出界限,直接跳出,找下一组
				  continue;
			  if(top.x==Ex&&top.y==Ey) //找到
			  {
				  cout<<"yes"<<endl;
				  return;
			  }
			  if(visit[top.x][top.y]>=top.step) //记录下转弯数,并入队列
			  { 
				  top.dir=u;
			  visit[top.x][top.y]=top.step;
			  Q.push(top);
			  }
	
	  }
  }
  cout<<"no"<<endl;
  return;
}
int main()
{
	int N;
	while(cin>>N)
	{	
		while(N--)
		{
			cin>>n>>m;
			memset(Map,0,sizeof(Map));
			int i,j;
			for(i=1;i<=n;i++)			
				for(j=1;j<=m;j++)				
				{
					cin>>Map[i][j];
					visit[i][j]=999;  //标记每一个位置的转弯情况
				}
			cin>>T>>Sy>>Sx>>Ey>>Ex;  //行列相反
			if(Sx==Ex&&Sy==Ey)
			{
				cout<<"yes"<<endl;
				continue;
			}
			BFS(Sx,Sy); //传上开始位置
		}
	}
	return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值