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
| #include <unordered_map> #include <algorithm> #include <iostream> #include <cstring> using namespace std; const int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1},inf=0x3f3f3f3f; unordered_map<char,int> char2digit = {{'N',0},{'S',2},{'E',1},{'W',3}}; unordered_map<int,char> digit2char = {{0,'N'},{2,'S'},{1,'E'},{3,'W'}}; int h,w,mem[40][40][4]; pair<int,int> from,to; char mp[40][40]; inline int lturn(int x){ int y = x - 1; return y==-1?3:y; } inline int rturn(int x){ int y = x + 1; return y==4?0:y; } inline int turnAround(int x){ int y = x + 2; return y % 4; } inline bool canWalkThrough(int x,int y,int dir){ return mp[x+dx[dir]][y+dy[dir]]!='.'; } void dfs(int x,int y,int cost,int dir){ if(cost>=mem[x][y][dir]) return; mem[x][y][dir] = cost; if(x==to.first&&y==to.second) return; bool flag=false; if(canWalkThrough(x,y,dir)) dfs(x+dx[dir],y+dy[dir],cost,dir),flag=true; int l=lturn(dir),r=rturn(dir); if(canWalkThrough(x,y,l)) dfs(x+dx[l],y+dy[l],cost+1,l),flag=true; if(canWalkThrough(x,y,r)) dfs(x+dx[r],y+dy[r],cost+5,r),flag=true; if(!flag){ int back = turnAround(dir); dfs(x,y,cost+10,back); } } int main(){ memset(mem,inf,sizeof(mem)); cin >> h >> w; for(int i=1;i<=h;i++){ for(int j=1;j<=w;j++){ cin >> mp[i][j]; if(isalpha(mp[i][j])){ if(mp[i][j]=='F') to = {i,j}; else from = {i,j}; } } } dfs(from.first,from.second,0,char2digit[mp[from.first][from.second]]); cout << min(mem[to.first][to.second][0],min(mem[to.first][to.second][1],min(mem[to.first][to.second][2],mem[to.first][to.second][3]))) << endl; return 0; }
|