Codeforces Round #516 (Div. 2)D. Labyrinth(BFS)

题目链接:http://codeforces.com/contest/1064/problem/D

题目大意:给你一个n*m的图,图中包含两种符号,'.'表示可以行走,'*'表示障碍物不能行走,规定最多只能向左走L个格子,向右R个格子,但是上下没有限制,现在给出出发点坐标(sx,sy),求能走的最大单元格数目。

 Examples

Input
Copy
4 5
3 2
1 2
.....
.***.
...**
*....
Output
Copy
10
Input
Copy
4 4
2 2
0 1
....
..*.
....
....
Output
Copy
7

解题思路:直接用BFS模拟行走过程,不过需要多记录下向左和向右行走的步数。为了保证保留向左向右行走的次数,我们优先向上下行走,能向上下行走就先不往左右行走。直接用双向队列,如果是向上下行走就放在队首,如果是左右行走放在队尾。

附上代码:

#include<bits/stdc++.h>
using namespace std;
int n,m,vis[2005][2005],ans,sx,sy,L,R;
int dir[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
char mp[2005][2005];
struct node{
    int x,y,l,r;
};
bool check(node x)
{
    if(x.x<=0||x.y<=0||x.x>n||x.y>m||vis[x.x][x.y]||mp[x.x][x.y]=='*')
        return false;
    return true;
}
void BFS()
{
    deque<node> que;
    vis[sx][sy]=1;
    ans++;
    node s;
    s.x=sx; s.y=sy; s.l=L; s.r=R;
    que.push_back(s);
    while(!que.empty())
    {
        node now=que.front();
        que.pop_front();
        node next;
        for(int i=0;i<4;i++)
        {
            next.x=now.x+dir[i][0];
            next.y=now.y+dir[i][1];
            if(check(next))
            {
                if(i<2)
                {
                    next.l=now.l; next.r=now.r;
                    que.push_front(next);
                    vis[next.x][next.y]=1;
                    ans++;
                }
                if(i==2&&now.l>=1)
                {
                    next.l=now.l-1;
                    next.r=now.r;
                    que.push_back(next);
                    vis[next.x][next.y]=1;
                    ans++;
                }
                if(i==3&&now.r>=1)
                {
                    next.l=now.l;
                    next.r=now.r-1;
                    que.push_back(next);
                    vis[next.x][next.y]=1;
                    ans++;
                }
            }
        }
    }
}
int main()
{
    scanf("%d%d%d%d%d%d",&n,&m,&sx,&sy,&L,&R);
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            cin>>mp[i][j];
    BFS();
    cout<<ans<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/zjl192628928/p/9791932.html