题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=988
搜索题目。
只不过把(x,y,d,c)作为一个结点。每个节点出发最多有三条边,分别对应前进、左转、右转。
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <map> #include <queue> #include <algorithm> using namespace std; #define Maxn 1005 #define INF 0x3f3f3f3f char g[30][30]; //x,y,d,c int vis[30][30][10][10]; int arrTime[30][30][10][10]; int disr[4] = {-1,0,1,0}; int disc[4] = {0,1,0,-1}; struct State { int x,y,d,c; State(){} State(int _x,int _y,int _d,int _c){x=_x,y=_y,d=_d,c=_c;} }s,t; int r,c; bool get(State tt) { if(tt.x == t.x && tt.y == t.y && tt.c == t.c) return true; return false; } bool inBound(State tt) { if(tt.x>=0 && tt.x<r && tt.y>=0 && tt.y<c) return true; return false; } int bfs() { queue<State> q; memset(vis,0,sizeof(vis)); memset(arrTime,0x3f,sizeof(arrTime)); q.push(s); vis[s.x][s.y][s.d][s.c] = 1; arrTime[s.x][s.y][s.d][s.c] = 0; while(!q.empty()) { State tmp = q.front(); q.pop(); State newS = State(tmp.x + disr[tmp.d],tmp.y + disc[tmp.d],tmp.d,(tmp.c+1)%5); if(inBound(newS) && !vis[newS.x][newS.y][newS.d][newS.c] && g[newS.x][newS.y]!='#') { vis[newS.x][newS.y][newS.d][newS.c] = 1; q.push(newS); arrTime[newS.x][newS.y][newS.d][newS.c] = arrTime[tmp.x][tmp.y][tmp.d][tmp.c] + 1; if(get(newS)) return arrTime[newS.x][newS.y][newS.d][newS.c]; } newS = State(tmp.x,tmp.y,(tmp.d-1+4)%4,tmp.c); if(!vis[newS.x][newS.y][newS.d][newS.c]) { vis[newS.x][newS.y][newS.d][newS.c] = 1; q.push(newS); arrTime[newS.x][newS.y][newS.d][newS.c] = arrTime[tmp.x][tmp.y][tmp.d][tmp.c] + 1; if(get(newS)) return arrTime[newS.x][newS.y][newS.d][newS.c]; } newS = State(tmp.x,tmp.y,(tmp.d+1)%4,tmp.c); if(!vis[newS.x][newS.y][newS.d][newS.c]) { vis[newS.x][newS.y][newS.d][newS.c] = 1; q.push(newS); arrTime[newS.x][newS.y][newS.d][newS.c] = arrTime[tmp.x][tmp.y][tmp.d][tmp.c] + 1; if(get(newS)) return arrTime[newS.x][newS.y][newS.d][newS.c]; } } return -1; } int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); #endif int cas = 0; while(scanf(" %d %d",&r,&c)!=EOF) { if(r == 0 || c == 0) continue; cas++; if(cas!=1) puts(""); printf("Case #%d\n",cas); for(int i=0;i<r;i++) scanf(" %s",g[i]); for(int i=0;i<r;i++) for(int j=0;j<c;j++) { if(g[i][j] == 'S') s = State(i,j,0,0); else if(g[i][j] == 'T') t = State(i,j,5,0); } int ans = bfs(); if(ans == -1) { puts("destination not reachable"); } else printf("minimum time = %d sec\n",ans ); } return 0; }