标签:
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 664 Accepted Submission(s): 307
1 /************************************************************************* 2 > File Name: code/hdu/2531.cpp 3 > Author: 111qqz 4 > Email: rkz2013@126.com 5 > Created Time: 2015年10月11日 星期日 23时14分43秒 6 ************************************************************************/ 7 8 #include<iostream> 9 #include<iomanip> 10 #include<cstdio> 11 #include<algorithm> 12 #include<cmath> 13 #include<cstring> 14 #include<string> 15 #include<map> 16 #include<set> 17 #include<queue> 18 #include<vector> 19 #include<stack> 20 #include<cctype> 21 22 #define yn hez111qqz 23 #define j1 cute111qqz 24 #define ms(a,x) memset(a,x,sizeof(a)) 25 using namespace std; 26 const int dx4[4]={1,0,0,-1}; 27 const int dy4[4]={0,-1,1,0}; 28 typedef long long LL; 29 typedef double DB; 30 const int inf = 0x3f3f3f3f; 31 const int N=1E2+5; 32 int w,h; 33 char maze[N][N]; 34 bool v[N][N]; 35 int cnt ; 36 int fx[30]; 37 int fy[30]; 38 struct node 39 { 40 int x,y; 41 int d; 42 bool ok() 43 { 44 if (x<0||y<0||x>=w||y>=h) return false; 45 if (maze[x][y]==‘O‘) return false; 46 if (v[x][y]) return false; 47 48 for ( int i =2 ; i <= cnt ; i++) 49 { 50 int xx = x + fx[i]; 51 int yy = y + fy[i]; 52 if (xx<0||yy<0||xx>=w||yy>=h) return false; 53 if (maze[xx][yy]==‘O‘) return false; 54 } 55 return true; 56 } 57 58 bool get() 59 { 60 if (maze[x][y]==‘Q‘) return true; 61 for ( int i = 2 ; i <= cnt ; i++) 62 { 63 int xx = x + fx[i]; 64 int yy = y + fy[i]; 65 if (maze[xx][yy]==‘Q‘) 66 { 67 return true; 68 } 69 } 70 return false; 71 } 72 }s; 73 74 bool bfs() 75 { 76 77 queue<node>q; 78 q.push(s); 79 80 while (!q.empty()) 81 { 82 node pre = q.front();q.pop(); 83 84 // printf("x: %d y: %d d: %d \n",pre.x,pre.y,pre.d); 85 86 if (pre.get()) 87 { 88 printf("%d\n",pre.d); 89 return true; 90 } 91 92 for ( int i = 0 ; i < 4 ; i++) 93 { 94 node next; 95 next.x = pre.x + dx4[i]; 96 next.y = pre.y + dy4[i]; 97 next.d = pre.d + 1; 98 if (next.ok()) 99 { 100 v[next.x][next.y] = true; 101 q.push(next); 102 } 103 } 104 } 105 return false; 106 107 } 108 int main() 109 { 110 #ifndef ONLINE_JUDGE 111 freopen("in.txt","r",stdin); 112 #endif 113 114 while (scanf("%d %d",&w,&h)!=EOF&&w&&h) 115 { 116 ms(v,false); 117 cnt = 0 ; 118 for ( int i = 0 ; i < w ; i++) scanf("%s",maze[i]); 119 120 for ( int i = 0 ; i < w ; i++) 121 for ( int j = 0 ; j < h ; j++) 122 { 123 if (maze[i][j]==‘D‘) 124 { 125 cnt++; 126 if (cnt==1) 127 { 128 fx[cnt] = i; 129 fy[cnt] = j; 130 s.x = i; 131 s.y = j; 132 s.d = 0 ; 133 v[i][j] = true; 134 } 135 else 136 { 137 fx[cnt] = i - fx[1]; //相对位移. 138 fy[cnt] = j - fy[1]; 139 } 140 } 141 } 142 143 if (!bfs()) 144 { 145 puts("Impossible"); 146 } 147 } 148 149 150 151 #ifndef ONLINE_JUDGE 152 fclose(stdin); 153 #endif 154 return 0; 155 }
标签:
原文地址:http://www.cnblogs.com/111qqz/p/4871356.html