搜索之转弯问题

点击打开链接

起初看了这个题没什么思路,后来偶然在其他oj上做了一道类似的也就明白了。

主要就是在一个点按照一个方向一直搜下去,直到不能搜。

这样再搜就会转弯了。

不多说,贴出代码


#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#define max 101
using namespace std;
int go[4][2] = {{-1,0},{0,-1},{0,1},{1,0}};
char a[max][max];
int vis[max][max];
int t,n,m,k;
int sx,sy,ex,ey;
struct node
{
    int x,y,step;
}s,e;
void bfs(int x1,int y1)
{
    memset(vis,0,sizeof(vis));
    s.x = x1, s.y = y1, s.step = -1;
    vis[x1][y1] = 1;


    queue<node>q;
    q.push(s);
    while(!q.empty())
    {
        s = q.front();
        if(s.step>=k)
        {
            cout << "NO" << endl;
            return;
        }
        q.pop();
        for(int i = 0; i < 4; i++)
        {
            e.x = s.x + go[i][0];
            e.y = s.y + go[i][1];
            e.step = s.step + 1;
            while(1)
            {
                if(e.x>=0&&e.x<n&&e.y>=0&&e.y<m&&a[e.x][e.y]=='.')
                {
                    if(e.x == ex&&e.y == ey)
                    {
                        cout << "YES" <<endl;
                        return ;
                    }
                    if(vis[e.x][e.y]==0)
                    {
                        vis[e.x][e.y] = 1;
                        q.push(e);
                    }
                    e.x+=go[i][0];
                    e.y+=go[i][1];
                }
                else
                    break;
            }
        }
    }
    cout << "NO" << endl;
}
int main()
{
    cin >> t;
    while(t--)
    {
        cin >> n >> m >> k;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
                 cin >> a[i][j];
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
               {
                     if(a[i][j] == 'S')
                     {
                        sx = i,sy = j;
                     }
                     if(a[i][j] == 'P')
                     {
                        ex = i,ey = j;
                        a[ex][ey] = '.';
                     }


               }


        bfs(sx,sy);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值