final exam

来源:互联网 发布:php 命名空间的用法 编辑:程序博客网 时间:2024/05/20 05:27
#include<iostream>#include<cstring>#include<queue>using namespace std;struct edge{int x,y,step;edge(int aa,int bb,int ss){x=aa;y=bb;step=ss;}edge(){}};int xpian[]={1,0,-1,0};int ypian[]={0,1,0,-1};int n,m,p1,p2;bool fl;queue<edge>que;char g[55][55];bool vi[55][55];edge bfs1(){edge temp;fl=0;while(!que.empty()){temp=que.front();que.pop();int aa=temp.x;int bb=temp.y;int stp=temp.step;if (aa==p1&&bb==p2){fl=1;return temp;}for (int i = 0; i < 4; ++i){int a1=aa+xpian[i];int b1=bb+ypian[i];int stp1=stp+1;if (a1>=0&&a1<=n-1&&b1>=0&&b1<=m-1&&g[a1][b1]!='#'&&vi[a1][b1]==0){que.push(edge(a1,b1,stp1));vi[a1][b1]=1;}}}return temp;}void bfs2(){edge temp;bool flag=0;while(!que.empty()){temp=que.front();que.pop();int aa=temp.x;int bb=temp.y;int stp=temp.step;if (aa==n-1&&bb==m-1){cout<<stp<<endl;flag=1;break;}for (int i = 0; i < 4; ++i){int a1=aa+xpian[i];int b1=bb+ypian[i];int stp1=stp+1;if (a1>=0&&a1<=n-1&&b1>=0&&b1<=m-1&&g[a1][b1]!='#'&&vi[a1][b1]==0){que.push(edge(a1,b1,stp1));vi[a1][b1]=1;}}}if(!flag){cout<<"-1"<<endl;}}int main(){while(cin>>n>>m){memset(vi,0,sizeof(vi));for (int i=0;i<n;i++){for (int j=0;j<m; j++){cin>>g[i][j];if(g[i][j]=='K'){p1=i;p2=j;}}}que=queue<edge>();que.push(edge(0,0,0));vi[0][0]=1;edge tem=bfs1();if(fl==0){cout<<"-1"<<endl;continue;}memset(vi,0,sizeof(vi));que=queue<edge>();que.push(tem);vi[tem.x][tem.y]=1;bfs2();}return 0;}

0 0
原创粉丝点击