# 最短路——BZOJ1656 [Usaco2006 Jan] The Grove 树木

http://www.lydsy.com/JudgeOnline/problem.php?id=1656

#include<bits/stdc++.h>
using namespace std;
struct ppap{int p,x,y;};
const int dx[9]={0,0,0,1,1,1,-1,-1,-1};
const int dy[9]={0,1,-1,0,1,-1,0,1,-1};
int n,m,sx,sy,d[2][51][51];
char c[51][51];
bool b[51][51]={0},rp[51][51]={0},a[51][51]={0};
queue<ppap>q;
inline void bfs(){
ppap jj;jj.p=0;jj.x=sx;jj.y=sy;d[0][sx][sy]=1;
q.push(jj);
while(!q.empty()){
ppap now=q.front();q.pop();int x,y;
for(int i=1;i<=8;i++){
x=now.x+dx[i];y=now.y+dy[i];
if(x<1||y<1||x>n||y>m||a[x][y])continue;
if(rp[now.x][now.y]&&y<=now.y)continue;
if(rp[x][y]&&y>now.y){
if(!d[1][x][y])d[1][x][y]=d[0][now.x][now.y]+1,
jj.x=x,jj.y=y,jj.p=1,
q.push(jj);
}else{if(!d[now.p][x][y])d[now.p][x][y]=d[now.p][now.x][now.y]+1,
jj.x=x,jj.y=y,jj.p=now.p,
q.push(jj);
}
}
}
}
int main()
{
scanf("%d%d",&n,&m);int px,py;
for(int i=1;i<=n;i++){
scanf("%s",c[i]+1);
for(int j=1;j<=m;j++){
if(c[i][j]=='X')a[i][j]=1,px=i,py=j;
if(c[i][j]=='*')sx=i,sy=j;
}
}
for(int i=px+1;i<=n;i++)rp[i][py]=1;
bfs();
printf("%d",d[1][sx][sy]-1);
return 0;
}

07-04 389
06-17 322
10-31 250
09-23 852
09-07 675
09-01 895
03-15 385
09-29 33
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客