标签:
1 #include<stdio.h> 2 #include<string.h> 3 #include<math.h> 4 #include<iostream> 5 #include<algorithm> 6 #include<queue> 7 #include<vector> 8 #include<set> 9 #include<stack> 10 #include<string> 11 #include<sstream> 12 #include<map> 13 #include<cctype> 14 using namespace std; 15 int n,m,b[4][2]={0,-1,0,1,-1,0,1,0},minn,Q1,Q2,visited[105][105],vis[105][105]; 16 char a[105][105]; 17 struct monkey 18 { 19 int x,y,step; 20 }; 21 queue<monkey>Q; 22 void pretreatment(int x,int y,char b,char c) //坐标 和 该名称 和 另一人名称 23 { 24 for(int i=x+1;i<m&&a[y][i]!=‘X‘&&a[y][i]!=c;i++) 25 a[y][i]=(a[y][i]==‘d‘?‘O‘:b+32); 26 for(int i=x-1;i>=0&&a[y][i]!=‘X‘&&a[y][i]!=c;i--) 27 a[y][i]=(a[y][i]==‘d‘?‘O‘:b+32); 28 for(int i=y+1;i<n&&a[i][x]!=‘X‘&&a[i][x]!=c;i++) 29 a[i][x]=(a[i][x]==‘d‘?‘O‘:b+32); 30 for(int i=y-1;i>=0&&a[i][x]!=‘X‘&&a[i][x]!=c;i--) 31 a[i][x]=(a[i][x]==‘d‘?‘O‘:b+32); 32 } 33 queue<monkey>W; 34 void BFSMORE(int x,int y,int step,char c) 35 { 36 monkey q={x,y,step}; 37 W.push(q); 38 while(!W.empty()) 39 { 40 monkey e=W.front(); 41 W.pop(); 42 for(int i=0;i<4;i++) 43 { 44 q.x=e.x+b[i][0],q.y=e.y+b[i][1]; 45 if(a[q.y][q.x]!=‘X‘&&a[q.y][q.x]!=‘D‘&&a[q.y][q.x]!=‘E‘&&q.x>=0&&q.x<m&&q.y>=0&&q.y<n&&!vis[q.y][q.x]) 46 { 47 vis[q.y][q.x]=1; 48 q.step=e.step+1; 49 W.push(q); 50 if(a[q.y][q.x]==c||a[q.y][q.x]==‘O‘) 51 { 52 minn=minn>q.step?q.step:minn; 53 while(!W.empty()) 54 W.pop(); 55 break; 56 } 57 } 58 } 59 } 60 } 61 void BFS(int x,int y) 62 { 63 monkey q={x,y,0}; 64 if(a[y][x]==‘O‘) 65 { 66 minn=0; 67 return ; 68 } 69 if(a[y][x]==‘d‘) 70 { 71 memset(vis,0,sizeof(vis)); 72 BFSMORE(x,y,0,‘e‘); 73 } 74 if(a[y][x]==‘e‘) 75 { 76 memset(vis,0,sizeof(vis)); 77 BFSMORE(x,y,0,‘d‘); 78 } 79 Q.push(q); 80 while(!Q.empty()) 81 { 82 monkey e=Q.front(); 83 Q.pop(); 84 for(int i=0;i<4;i++) 85 { 86 q.x=e.x+b[i][0],q.y=e.y+b[i][1]; 87 if(a[q.y][q.x]!=‘X‘&&a[q.y][q.x]!=‘D‘&&a[q.y][q.x]!=‘E‘&&q.x>=0&&q.x<m&&q.y>=0&&q.y<n&&!visited[q.y][q.x]) 88 { 89 q.step=e.step+1; 90 Q.push(q); 91 visited[q.y][q.x]=1; 92 if(a[q.y][q.x]==‘d‘) 93 { 94 memset(vis,0,sizeof(vis)); 95 BFSMORE(q.x,q.y,q.step,‘e‘); 96 } 97 if(a[q.y][q.x]==‘e‘) 98 { 99 Q2=1; 100 memset(vis,0,sizeof(vis)); 101 BFSMORE(q.x,q.y,q.step,‘d‘); 102 } 103 } 104 } 105 } 106 } 107 int main() 108 { 109 int sx,sy,dx,dy,ex,ey,t,count1=0; 110 while(scanf("%d%d%d",&n,&m,&t)!=EOF) 111 { 112 minn=t+1; 113 for(int i=0;i<n;i++) 114 { 115 for(int j=0;j<m;j++) 116 { 117 scanf(" %c",&a[i][j]); 118 if(a[i][j]==‘S‘) 119 { 120 sx=j; 121 sy=i; 122 } 123 if(a[i][j]==‘D‘) 124 { 125 dx=j; 126 dy=i; 127 } 128 if(a[i][j]==‘E‘) 129 { 130 ex=j; 131 ey=i; 132 } 133 } 134 } 135 pretreatment(dx,dy,‘D‘,‘E‘); 136 pretreatment(ex,ey,‘E‘,‘D‘); 137 memset(visited,0,sizeof(visited)); 138 visited[sy][sx]=1; 139 BFS(sx,sy); 140 printf("Case %d:\n",++count1); 141 if(minn<=t) 142 printf("%d\n",minn); 143 else 144 printf("-1\n"); 145 } 146 return 0; 147 }
标签:
原文地址:http://www.cnblogs.com/A-FM/p/5348326.html