来源 codeforces 2020 GDUT Rating Contest II (Div. 2) CF链接
题目:
A fire has broken out on the farm, and the cows are rushing to try and put it out! The farm is described by a 10×10 grid of characters like this: …B…R…L… The character ‘B’ represents the barn, which has just caught on fire. The ‘L’ character represents a lake, and ‘R’ represents the location of a large rock.
The cows want to form a “bucket brigade” by placing themselves along a path between the lake and the barn so that they can pass buckets of water along the path to help extinguish the fire. A bucket can move between cows if they are immediately adjacent in the north, south, east, or west directions. The same is true for a cow next to the lake — the cow can only extract a bucket of water from the lake if she is immediately adjacent to the lake. Similarly, a cow can only throw a bucket of water on the barn if she is immediately adjacent to the barn.
Please help determine the minimum number of ‘.’ squares that should be occupied by cows to form a successful bucket brigade.
A cow cannot be placed on the square containing the large rock, and the barn and lake are guaranteed not to be immediately adjacent to each-other.
Input
The input file contains 10 rows each with 10 characters, describing the layout of the farm.
Output
Output a single integer giving the minimum number of cows needed to form a viable bucket brigade.
Example
input
…
…
…
…B…
…
…R…
…
…
…L…
…
output
7
题意:给定1010的图,求L到B的最短路径长度,R为路障不可同行。
思路:一般使用bfs求解,考虑到图只有1010dfs应该也能ac。
还可以使用数学方法求解。数学方法链接
BFS代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<queue>
#define INF 0x3f3f3f3f
#define mod 1000000007
using namespace std;
struct node
{
int x,y;
};
int a[11][11],xd[]={1,-1,0,0},yd[]={0,0,1,-1},visit[11][11];
int xs,ys,xf,yf,ans;
void bfs(int n,int m)
{
int x,y;
queue<node> q;
q.push(node{n,m});
while (!q.empty())
{
node pre=q.front();
for (int i=0;i<4;i++)
{
x=pre.x+xd[i];
y=pre.y+yd[i];
if (x>=1 && y>=1 && x<=10 && y<=10 && a[x][y]!=INF && !visit[x][y])
{
if (x==xf && y==yf)
{
ans=a[pre.x][pre.y];
return;
}
q.push(node{x,y});
a[x][y]=a[pre.x][pre.y]+1;
visit[x][y]=1;
}
}
q.pop();
}
}
int main()
{
char str[10];
for (int i=1;i<=10;i++)
{
scanf("%s",str);
for (int j=0;j<10;j++)
{
if (str[j]=='R') a[i][j+1]=INF;
if (str[j]=='L') xs=i,ys=j+1;
if (str[j]=='B') xf=i,yf=j+1;
}
}
bfs(xs,ys);
cout<<ans;
return 0;
}