假期做的搜索 现在才想起来补上……
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cmath> 5 #include<cstring> 6 #include<string> 7 #include<ctime> 8 #include<map> 9 #include<set> 10 #include<vector> 11 #include<queue> 12 #include<cstdlib> 13 #include<cassert> 14 #include<sstream> 15 #include<stack> 16 #include<list> 17 #include<bitset> 18 #define cl(a,b) memset(a,b,sizeof(a)) 19 #define debug(x) cerr<<#x<<"=="<<(x)<<endl 20 using namespace std; 21 typedef long long ll; 22 typedef long double ldb; 23 typedef pair<int,int> pii; 24 25 const int inf=0x3f3f3f3f; 26 const int maxn=30; 27 const int mod=1e7+7; 28 const double eps=1e-8; 29 const double pi=acos(-1); 30 31 int dx[8]= {-1,0,1,0}; 32 int dy[8]= {0,1,0,-1}; 33 34 struct point 35 { 36 int x,y,col,dir,time; 37 }; 38 39 int n,m; 40 char mp[maxn][maxn]; 41 bool vis[maxn][maxn][5][5]; 42 point st,ed; 43 44 void init() 45 { 46 cl(vis,false); 47 } 48 49 bool check(point x) 50 { 51 if(x.x<0||x.x>=n 52 ||x.y<0||x.y>=m 53 ||mp[x.x][x.y]=='#' 54 ||vis[x.x][x.y][x.dir][x.col]) 55 return false; 56 return true; 57 } 58 59 int bfs() 60 { 61 queue<point>pt; 62 while(!pt.empty()) pt.pop(); 63 pt.push(st); 64 while(!pt.empty()) 65 { 66 point tp=pt.front(); 67 point tmp=tp; 68 pt.pop(); 69 if(tmp.x==ed.x&&tmp.y==ed.y&&tmp.col==ed.col) return tmp.time; 70 tmp.x+=dx[tmp.dir]; 71 tmp.y+=dy[tmp.dir]; 72 tmp.col=(tmp.col+1)%5;//向相应的方向走一步 73 if(check(tmp)) 74 { 75 vis[tmp.x][tmp.y][tmp.dir][tmp.col]=1; 76 tmp.time++; 77 pt.push(tmp); 78 } 79 tmp=tp; 80 tmp.dir=(tp.dir+1)%4;//向右转 81 if(check(tmp)) 82 { 83 vis[tmp.x][tmp.y][tmp.dir][tmp.col]=1; 84 tmp.time++; 85 pt.push(tmp); 86 } 87 tmp=tp; 88 tmp.dir=(tp.dir+3)%4;//向左转 89 if(check(tmp)) 90 { 91 vis[tmp.x][tmp.y][tmp.dir][tmp.col]=1; 92 tmp.time++; 93 pt.push(tmp); 94 } 95 } 96 return -1; 97 } 98 99 int main() 100 { 101 int cas=1; 102 while(~scanf("%d%d",&n,&m)) 103 { 104 if(n==0&&m==0) break; 105 init(); 106 for(int i=0;i<n;i++) 107 { 108 scanf("%s",mp[i]); 109 for(int j=0;j<m;j++) 110 { 111 if(mp[i][j]=='S') 112 {//起点 113 st.x=i,st.y=j,st.dir=0,st.col=0; 114 vis[i][j][0][0]=1; 115 } 116 if(mp[i][j]=='T') 117 {//终点 118 ed.x=i,ed.y=j,ed.col=0; 119 } 120 } 121 } 122 if(cas!=1) printf(" ");//cas!=1 123 printf("Case #%d ",cas++); 124 int ans=bfs(); 125 if(ans==-1) printf("destination not reachable "); 126 else printf("minimum time = %d sec ",ans); 127 } 128 return 0; 129 } 130 /* 131 132 1 3 133 S#T 134 10 10 135 #S.......# 136 #..#.##.## 137 #.##.##.## 138 .#....##.# 139 ##.##..#.# 140 #..#.##... 141 #......##. 142 ..##.##... 143 #.###...#. 144 #.....###T 145 0 0 146 147 */