标签:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 #include <algorithm> 6 using namespace std; 7 const int INF = 0x3f3f3f3f; 8 char direct[4] = {‘D‘,‘L‘,‘R‘,‘U‘},path[10000]; 9 int n,m,dis[600][600],cnt; 10 int gx[4] = {1,0,0,-1}; 11 int gy[4] = {0,-1,1,0}; 12 char g[600][600]; 13 struct point 14 { 15 int x,y; 16 }; 17 void bfs(int x,int y) 18 { 19 queue<point> q; 20 point temp,temp2; 21 temp.x = x; 22 temp.y = y; 23 q.push(temp); 24 while(q.size()) 25 { 26 temp2 = q.front(); 27 q.pop(); 28 if(temp2.x == n && temp2.y == m) 29 { 30 return; 31 } 32 for(int i = 0; i < 4; i++) 33 { 34 int fx = gx[i] + temp2.x; 35 int fy = gy[i] + temp2.y; 36 if(fx >= 1 && fx <= n && fy >= 1 && fy <= m && g[fx][fy] == ‘0‘ && dis[fx][fy] > dis[temp2.x][temp2.y] + 1) 37 { 38 dis[fx][fy] = dis[temp2.x][temp2.y] + 1; 39 temp.x = fx; 40 temp.y = fy; 41 q.push(temp); 42 } 43 } 44 } 45 } 46 int dfs(int x,int y,int ans) 47 { 48 if(x == n && y == m) 49 { 50 cnt = ans; 51 return true; 52 } 53 for(int i = 0; i < 4; i++) 54 { 55 int fx = x + gx[i]; 56 int fy = y + gy[i]; 57 if(fx >= 1 && fx <= n && fy <= m && fy >= 1 && dis[x][y] + 1 == dis[fx][fy]) 58 { 59 path[ans] = direct[i]; 60 if(dfs(fx,fy,ans + 1)) //不满足要回溯! 61 return true; 62 } 63 } 64 return false; 65 } 66 int main() 67 { 68 scanf("%d%d", &n, &m); 69 getchar(); 70 for(int i = 1; i <= n; i++) 71 { 72 for(int j = 1; j <= m; j++) 73 { 74 scanf("%c", &g[i][j]); 75 } 76 getchar(); 77 } 78 memset(dis, INF, sizeof(dis)); 79 dis[1][1] = 0; 80 cnt = 0; 81 bfs(1,1); 82 dfs(1,1,0); 83 printf("%d\n", dis[n][m]); 84 path[cnt] = ‘\0‘; 85 printf("%s\n", path); 86 return 0; 87 }
标签:
原文地址:http://www.cnblogs.com/zhaopAC/p/5086988.html