Time Limit: 3000/1000 MS
(Java/Others) Memory Limit: 32768/32768 K
(Java/Others)
Total Submission(s): 990 Accepted
Submission(s): 378
1 #include<iostream> 2 #include<stdio.h> 3 #include<cstring> 4 #include<cstdlib> 5 #include<queue> 6 using namespace std; 7 8 int n,m; 9 char a[101][101]; 10 bool dp[101][101][(1<<4)+1]; 11 int map1[4][2]={{1,0},{0,1},{0,-1},{-1,0}}; 12 struct node 13 { 14 int x,y; 15 int state; 16 int time; 17 }; 18 queue<node>Q; 19 20 int get(char cc) 21 { 22 if(cc==‘B‘ || cc==‘b‘)return 0; 23 else if(cc==‘Y‘ || cc==‘y‘)return 1; 24 else if(cc==‘R‘ || cc==‘r‘)return 2; 25 else return 3; 26 } 27 int bfs(int x,int y) 28 { 29 int i,x1,y1,state; 30 struct node t,cur; 31 32 t.x=x; 33 t.y=y; 34 t.time=0; 35 t.state=0; 36 dp[x][y][0]=true; 37 Q.push(t); 38 while(!Q.empty()) 39 { 40 t=Q.front(); 41 Q.pop(); 42 for(i=0;i<4;i++) 43 { 44 x1=t.x+map1[i][0]; 45 y1=t.y+map1[i][1]; 46 if(x1>=0&&x1<n && y1>=0&&y1<m && a[x1][y1]!=‘#‘) 47 { 48 if(a[x1][y1]==‘X‘) 49 { 50 printf("Escape possible in %d steps.\n",t.time+1); 51 return 1; 52 } 53 if(a[x1][y1]>=‘A‘&&a[x1][y1]<=‘Z‘) 54 { 55 state=(1<<get(a[x1][y1])); 56 if( (t.state&state)==state && dp[x1][y1][t.state]==false) 57 { 58 dp[x1][y1][t.state]=true; 59 cur=t; 60 cur.time++; 61 cur.x=x1; 62 cur.y=y1; 63 Q.push(cur); 64 } 65 } 66 else if(a[x1][y1]>=‘a‘&&a[x1][y1]<=‘z‘) 67 { 68 state=(1<<get(a[x1][y1])); 69 cur=t; 70 cur.state=(cur.state|state); 71 if(dp[x1][y1][cur.state]==false) 72 { 73 dp[x1][y1][cur.state]=true; 74 cur.x=x1; 75 cur.y=y1; 76 cur.time++; 77 Q.push(cur); 78 } 79 } 80 else if(dp[x1][y1][t.state]==false) 81 { 82 dp[x1][y1][t.state]=true; 83 cur.x=x1; 84 cur.y=y1; 85 cur.state=t.state; 86 cur.time=t.time+1; 87 Q.push(cur); 88 } 89 } 90 } 91 } 92 return -1; 93 } 94 int main() 95 { 96 int i,j,x,y,k; 97 bool cur; 98 while(scanf("%d%d",&n,&m)>0) 99 { 100 if(n==0&&m==0)break; 101 memset(dp,false,sizeof(dp)); 102 while(!Q.empty()) 103 { 104 Q.pop(); 105 } 106 for(i=0;i<n;i++) 107 scanf("%s",a[i]); 108 cur=false; 109 for(i=0;i<n;i++) 110 { 111 for(j=0;j<m;j++) 112 { 113 if(a[i][j]==‘*‘) 114 { 115 x=i; 116 y=j; 117 } 118 if(a[i][j]==‘X‘) 119 cur=true; 120 } 121 } 122 if(cur==false) printf("The poor student is trapped!\n"); 123 else 124 { 125 k=bfs(x,y); 126 if(k==-1)printf("The poor student is trapped!\n"); 127 } 128 } 129 return 0; 130 }
原文:http://www.cnblogs.com/tom987690183/p/3641344.html