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

时间:2023-03-09 17:22:21
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[][],ans,sx,sy,L,R;
int dir[][]={{,},{-,},{,-},{,}};
char mp[][];
struct node{
int x,y,l,r;
};
bool check(node x)
{
if(x.x<=||x.y<=||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]=;
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=;i<;i++)
{
next.x=now.x+dir[i][];
next.y=now.y+dir[i][];
if(check(next))
{
if(i<)
{
next.l=now.l; next.r=now.r;
que.push_front(next);
vis[next.x][next.y]=;
ans++;
}
if(i==&&now.l>=)
{
next.l=now.l-;
next.r=now.r;
que.push_back(next);
vis[next.x][next.y]=;
ans++;
}
if(i==&&now.r>=)
{
next.l=now.l;
next.r=now.r-;
que.push_back(next);
vis[next.x][next.y]=;
ans++;
}
}
}
}
}
int main()
{
scanf("%d%d%d%d%d%d",&n,&m,&sx,&sy,&L,&R);
for(int i=;i<=n;i++)
for(int j=;j<=m;j++)
cin>>mp[i][j];
BFS();
cout<<ans<<endl;
return ;
}