HDU 1175 BFS

每次进行一次"彻底"的搜索.所谓彻底的搜索,就是一次性一条直线走过去,因为我们转了一个弯之后无论走多远都不会增加转弯数;

0123
0000
0121
0000

比如上面这个表格,我们从 (4,3)    1出来后往下,转弯数量为1(我们也记录一次转弯,最后判断转弯数不超过3而不是2)

到达(4,4)  再转个弯往左走,我们可以一直走到(4,1) 都算2个弯.这就是 一次 "彻底" 的搜索!


/*
 *HDU 1175
 *fuqiang11
 *BFS
 *2013/7/30
 *关于转弯次数,本来第一次 出去不计入方向,但是我们计入进去,所以最终判断他不超过3个弯,而不是2个
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cstdlib>
using namespace std;
#define maxn 1000+3

int map[maxn][maxn];
bool vis[maxn][maxn];
int xx[] = {0,0,1,-1};
int yy[] = {1,-1,0,0};
int n,m;
struct point
{
    int x;
    int y;
    int turn;
};

bool check(int x, int y)
{
    if(x<1||y<1||x>n||y>m||vis[x][y])
        return false;
    return true;
}

queue <point> q;
int BFS(point st, point ed)
{
    memset(vis,false,sizeof(vis));
    while(!q.empty())
        q.pop();
    st.turn = 0;
    q.push(st);
    vis[st.x][st.y] = true;
    point a,b;
    while(!q.empty())
    {
        a = q.front();
        q.pop();
        if(a.turn >= 3)  //目前到达的点已经转了3个弯了.再转就超过了.
            return 0;
        for(int i = 0; i < 4; i++)
        {
            b.x = a.x + xx[i];
            b.y = a.y + yy[i];
            b.turn = a.turn + 1;
            while(check(b.x, b.y) && map[b.x][b.y]==0)
            {
                q.push(b);
                vis[b.x][b.y] = true;
                b.x += xx[i];
                b.y += yy[i];
            }
            if(check(b.x, b.y))
            {
                if(b.x == ed.x && b.y == ed.y)  //能到达终点
                {
                    if(b.turn <= 3)
                        return 1;
                }
            }

        }
    }
    return 0;
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("in","r",stdin);
#endif
    int q;
    point st,ed;
    while(scanf("%d%d",&n,&m)&&(n+m))
    {
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= m; j++)
                scanf("%d",&map[i][j]);
        scanf("%d",&q);
        while(q--)
        {
            scanf("%d%d%d%d",&st.x,&st.y,&ed.x,&ed.y);
            if(map[st.x][st.y] != map[ed.x][ed.y]) //连的块不一样,直接输出 NO
                puts("NO");
            else
            if(BFS(st,ed))   //找到
                puts("YES");
            else
                puts("NO");
        }
    }
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值