1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
| #include<bits/stdc++.h> using namespace std;
typedef pair<int,int> pint; const int N=50+5,M=N*N*N+5,INF=0x3f3f3f3f; const int dx[]={-1,0,1,0},dy[]={0,1,0,-1}; char g[N][N]; pint st,ed; int n,m,len;
int Idx(int a,int b,int c){ return (a*m+b)*(len+1)+c; }
struct Adj{int v,w;}; vector<Adj> a[M];
int SPFA(){ static int dis[M]; static bool inQ[M]; int h=Idx(st.first,st.second,0); memset(dis,0x3f,sizeof(dis)); dis[h]=0; deque<int> q; q.push_back(h); while(!q.empty()){ int u=q.front(); q.pop_front(); for(auto e:a[u]){ if(dis[e.v]>dis[u]+e.w){ dis[e.v]=dis[u]+e.w; if(!inQ[e.v]){ if(!q.empty() && dis[q.front()]>dis[e.v]) q.push_front(e.v); else q.push_back(e.v); inQ[e.v]=1; } } } inQ[u]=0; }
int ans=INF; for(int i=0;i<=len;i++) ans=min(ans,dis[Idx(ed.first,ed.second,i)]);
return ans; }
bool isLegal(int x,int y){ if(x<0||x>=n)return 0; if(y<0||y>=m)return 0; if(g[x][y]=='#')return 0; return 1; }
int op[N]; void AddEdge(){ for(int i=0;i<n;i++) for(int j=0;j<m;j++) for(int k=0;k<=len;k++){ if(!isLegal(i,j))continue;
if(k<len){ int nx=i+dx[op[k+1]]; int ny=j+dy[op[k+1]]; if(isLegal(nx,ny)){ int u=Idx(i,j,k); int v=Idx(nx,ny,k+1); a[u].push_back(Adj{v,0}); }else{ int u=Idx(i,j,k); int v=Idx(i,j,k+1); a[u].push_back(Adj{v,0}); } }
if(k<len){ int u=Idx(i,j,k); int v=Idx(i,j,k+1); a[u].push_back(Adj{v,1}); }
for(int l=0;l<4;l++){ int nx=i+dx[l]; int ny=j+dy[l]; if(isLegal(nx,ny)){ int u=Idx(i,j,k); int v=Idx(nx,ny,k); a[u].push_back(Adj{v,1}); } } } }
int main(){ cin>>n>>m; for(int i=0;i<n;i++) for(int j=0;j<m;j++){ cin>>g[i][j]; if(g[i][j]=='S')st=make_pair(i,j); if(g[i][j]=='G')ed=make_pair(i,j); }
string s; cin>>s; len=s.length(); for(int i=0;i<len;i++){ if(s[i]=='U')op[i+1]=0; else if(s[i]=='R')op[i+1]=1; else if(s[i]=='D')op[i+1]=2; else if(s[i]=='L')op[i+1]=3; }
AddEdge(); cout<<SPFA(); return 0; }
|