# BFS【bzoj1667】: [Usaco2006 Oct]Cows on Skates滑旱冰的奶牛

## 1667: [Usaco2006 Oct]Cows on Skates滑旱冰的奶牛

#### Description

code：

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

int sum=0,f=1; char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
while(ch>='0'&&ch<='9'){sum=(sum<<1)+(sum<<3)+ch-'0'; ch=getchar();}
return sum*f;
}

const int wx=517;

struct node{
int x,y;
};

int dx[]={0,1,0,-1,0};
int dy[]={0,0,1,0,-1};

int vis[wx][wx];
int a[wx][wx],ansx[wx],ansy[wx];
char c[wx];
int prex[wx][wx];int prey[wx][wx];
int n,m,ans,num,tot,cnt;
int xx[wx],yy[wx],dis[wx][wx];

queue<node >q;

void bfs(){
memset(dis,0x3f,sizeof dis);
dis[1][1]=0; q.push((node){1,1});
while(q.size()){
int ux=q.front().x; int uy=q.front().y;
q.pop();
for(int i=1;i<=4;i++){
int ex=ux+dx[i]; int ey=uy+dy[i];
if(ex<1||ex>n||ey<1||ey>m||a[ex][ey])continue;
if(dis[ex][ey]>dis[ux][uy]+1){
dis[ex][ey]=dis[ux][uy]+1;
q.push((node){ex,ey});
prex[ex][ey]=ux; prey[ex][ey]=uy;
}
}
}
}

int main(){
for(int i=1;i<=n;i++){
scanf("%s",c+1);
for(int j=1;j<=m;j++){
a[i][j]=(c[j]=='*');
}
}
bfs();
int nowx=n; int nowy=m;
while(nowx){
ansx[++tot]=nowx; ansy[tot]=nowy;
int tmp=nowx;
nowx=prex[tmp][nowy]; nowy=prey[tmp][nowy];
}
for(int i=tot;i>=1;i--){
printf("%d %d\n",ansx[i],ansy[i]);
}
return 0;
}

posted @ 2018-10-19 21:10  _王小呆  阅读(124)  评论(0编辑  收藏  举报