BFS hdu 1728 逃离迷宫 转弯数

可以用BFS,此题不同的是每次从一个点扩展时,是把满足条件的这一行和一列入队(便于更新转弯数)。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#define maxn 105
#define INF 99999999
#define lson step<<1
#define rson step<<1|1
using namespace std;
int n,m;
int startx,starty,endx,endy;
int k;
char mapp[maxn][maxn];
bool book[maxn][maxn];
struct node
{
	int x,y,w;
};
void bfs(int sx,int sy,int gx,int gy)
{
	memset(book,false,sizeof(book));
	queue<node>q;
	node h,fw;
	h.x=sx;
	h.y=sy;
	h.w=-1;
	q.push(h);
	int tx,ty;
	int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};	
	int flag=0;
	while(!q.empty())
	{
		h=q.front();
		q.pop();
		for(int i=0;i<4;i++)
		{
			tx=h.x+next[i][0];
			ty=h.y+next[i][1];
			while(tx>=0&&tx<n&&ty>=0&&ty<m&&mapp[tx][ty]=='.')
			{
				if(book[tx][ty]==false)
				{
					book[tx][ty]=true;
					fw.x=tx;
					fw.y=ty;
					fw.w=h.w+1;
					q.push(fw);
				}
				if(tx==gx&&ty==gy&&fw.w<=k)
				{
					flag=1;
					break;
				}	
				tx=tx+next[i][0];
				ty=ty+next[i][1];
			}
			if(flag)
				break;
		}
		if(flag)
			break;
	}
	if(flag)
		cout << "yes\n";
	else
		cout << "no\n";
}
int main()
{
    //ios::sync_with_stdio(false);
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d %d",&n,&m);
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                cin>>mapp[i][j];
                //scanf("%c",&mapp[i][j]);    
            }    
        }    
        //cin>>k>>starty>>startx>>endy>>endx;
        scanf("%d %d %d %d %d",&k,&starty,&startx,&endy,&endx);
        starty--;startx--;endy--;endx--;
        
        book[startx][starty]=true;
        bfs(startx,starty,endx,endy);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值