1 /*一个网格迷宫由n行m列的单元格组成,每个单元格要么是空地(用1来表示),要么是障碍物(用0来表示).你的任务是找一条从起点到终点的最短移动序列,其中UDLR分别表示往上下左右移动到相邻单元格.任何时候会都不能在障碍格中,也不能走到迷宫之外,起点和终点保证是空地.n,m<=100. 2 3 思路很简单:不断沿着父亲指针走,保存方向序列dir,最后反向输出.不能用递归,要用递归会出现栈溢出的现象,所以把dir数组声明成全局变量. 4 5 代码如下:*/ 6 7 #include <iostream> 8 9 #include <queue> 10 11 using namespace std ; 12 13 const int MAXN = 105 ; 14 15 int dx[] = {-1,1,0,0} ; 16 17 int dy[] = {0,0,-1,1} ; 18 19 char name[] = "UDLR" ; 20 21 int n , m , nx , ny ; 22 23 int maze[MAXN][MAXN] , vis[MAXN][MAXN] , fa[MAXN][MAXN] , dist[MAXN][MAXN] , last_dir[MAXN][MAXN] ; 24 25 queue<int> q ; 26 27 void Bfs(int x , int y) 28 29 { 30 31 int u ; 32 33 u = m*x+y ; 34 35 vis[x][y] = 1 ; 36 37 dist[x][y] = 0 ; 38 39 fa[x][y] = u ; 40 41 q.push(u) ; 42 43 while (!q.empty()) 44 45 { 46 47 u = q.front() ; 48 49 q.pop() ; 50 51 x = u/m ; 52 53 y = u%m ; 54 55 for (int i = 0 ; i < 4 ; ++ i) 56 57 { 58 59 nx = x+dx[i] ; 60 61 ny = y+dy[i] ; 62 63 if (nx >= 0 && nx < n && ny >= 0 && ny < m && maze[nx][ny] && !vis[nx][ny]) 64 65 { 66 67 int v = nx * m + ny ; 68 69 vis[nx][ny] = 1 ; 70 71 fa[nx][ny] = u ; 72 73 dist[nx][ny] = dist[x][y] + 1 ; 74 75 q.push(v) ; 76 77 last_dir[nx][ny] = i ; 78 79 } 80 81 } 82 83 } 84 85 } 86 87 void Print_path(int x , int y) 88 89 { 90 91 int fx = fa[x][y]/m ; 92 93 int fy = fa[x][y]%m ; 94 95 if (fx != x || fy != y) 96 97 { 98 99 Print_path(fx,fy) ; 100 101 cout << name[last_dir[x][y]] ; 102 103 } 104 105 } 106 107 int dir[MAXN*MAXN] ; 108 109 void Print_path2(int x , int y) 110 111 { 112 113 int c = 0 ; 114 115 while (true) 116 117 { 118 119 int fx = fa[x][y]/m ; 120 121 int fy = fa[x][y]%m ; 122 123 if (fx == x && fy == y) 124 125 { 126 127 break ; 128 129 } 130 131 dir[c++] = last_dir[x][y] ; 132 133 x = fx ; 134 135 y = fy ; 136 137 } 138 139 while (c--) 140 141 { 142 143 cout << name[dir[c]] ; 144 145 } 146 147 } 148 149 int main() 150 151 { 152 153 int i , j ; 154 155 int xs,ys,xt,yt ; 156 157 cin >> n >> m >> xs >> ys >> xt >> yt ; 158 159 for (i = 0 ; i < n ; ++ i) 160 161 { 162 163 for (j = 0 ; j < m ; ++ j) 164 165 { 166 167 cin >> maze[i][j] ; 168 169 } 170 171 } 172 173 memset(vis,0,sizeof(vis)) ; 174 175 Bfs(xs,ys) ; 176 177 Print_path(xt,yt) ; 178 179 cout << endl ; 180 181 return 0 ; 182 183 }
View Code