题目链接:https://uva.onlinejudge.org/external/100/10047.pdf
题目链接:http://vjudge.net/contest/132239#problem/B
《训练指南》P308
没什么好说的,学习一下刘汝佳的风格。
#include <bits/stdc++.h> using namespace std; #define INF 0x3f3f3f3f int R,C; const int maxr = 25 + 5; const int maxc = 25 + 5; char maze[maxr][maxc]; int sr,sc,tr,tc; int ans; struct State { int r,c,dir,color; State(int r,int c,int dir,int color) : r(r),c(c),dir(dir),color(color) {} }; const int dr[] = {-1,0,1,0}; const int dc[] = {0,-1,0,1}; int d[maxr][maxc][4][5],vis[maxr][maxc][4][5]; queue <State> Q; void update (int r,int c,int dir,int color,int v) { if(r<0||r>=R||c<0||c>=C) return; if(maze[r][c]=='.'&&!vis[r][c][dir][color]) { Q.push(State(r,c,dir,color)); vis[r][c][dir][color] = 1; d[r][c][dir][color] = v; if(r==tr&&c==tc&&color==0) ans = min(ans,v); } } void bfs(State st) { Q.push(st); d[st.r][st.c][st.dir][st.color] = 0; vis[st.r][st.c][st.dir][st.color] = 1; while(!Q.empty()) { st = Q.front(); Q.pop(); int v = d[st.r][st.c][st.dir][st.color] + 1; update (st.r,st.c,(st.dir+1)%4, st.color, v); update (st.r,st.c,(st.dir+3)%4, st.color, v); update (st.r+dr[st.dir],st.c + dc[st.dir],st.dir,(st.color+1)%5,v); } } int main() { int cases = 0; //freopen("input.txt","r",stdin); while(scanf("%d%d",&R,&C),R) { for(int i=0;i<R;i++) { scanf("%s",maze[i]); { for(int j=0;j<C;j++) { if(maze[i][j]=='S') { sr = i; sc = j; } else if(maze[i][j]=='T') { tr = i; tc = j; } } } } maze[sr][sc] = maze[tr][tc] = '.'; ans = INF; memset(vis,0,sizeof(vis)); bfs(State(sr,sc,0,0)); if(cases>0) printf("\n"); printf("Case #%d\n",++cases); if(ans==INF) printf("destination not reachable\n"); else printf("minimum time = %d sec\n", ans); } return 0; }