const int MaxN = 105; int n, m; int maze[MaxN][MaxN]; bool vis[MaxN][MaxN]; int fa[MaxN][MaxN], dist[MaxN][MaxN], last_dir[MaxN][MaxN];
///u, d, l, r int dx[4] = {0, 0, -1, 1}; int dy[4] = {1, -1, 0, 0}; char name[4] = {'r', 'l', 'u', 'd'};
bool inbound(int x, int l, int r) { if (x >= l) if (x < r) return true; else return false; else return false; }
void bfs(int x, int y) { int d = 0; int u = x * m + y; vis[x][y] = 1; fa[x][y] = u; dist[x][y] = 0; queue<int> q; q.push(u); while (!q.empty()) { u = q.front(); q.pop(); x = u / m; y = u % m; for (d = 0; d < 4; d++) { int nx = x + dx[d]; int ny = y + dy[d]; if (inbound(nx, 0, n) && inbound(ny, 0, m) && maze[nx][ny] && !vis[nx][ny]) { int v = nx * m + ny; q.push(v); vis[nx][ny] = 1; fa[nx][ny] = u; //cout<<"fa:"<<" nx:"<<nx<<" ny:"<<ny<<" u:"<<u<<endl; dist[nx][ny] = dist[x][y] + 1; last_dir[nx][ny] = d; // cout<<"dir: "<<d<<endl; } } } return; }
void init() { freopen("maze.in", "r", stdin); scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) scanf("%d", &maze[i][j]); puts("打印迷宫:"); printf("i \\ j "); for (int j = 0; j < m; j++) printf("%7d:", j); printf("\n"); for (int i = 0; i < n; i++) { printf("%4d: ", i); for (int j = 0; j < m - 1; j++) printf("%8d", maze[i][j]); printf("%8d\n", maze[i][m - 1]); } puts("输入终点坐标"); bfs(0, 0); }
void print(int x, int y) { stack<int> dir; cout<<endl; while (true) { int fx = fa[x][y] / m; int fy = fa[x][y] % m; // cout<<" fx:"<fx<<" fy:"<<fy<<endl; //cout<<" x:"<<x<<" y:"<<y<<endl; if (fx == x && fy == y) break; dir.push(last_dir[x][y]); x = fx; y = fy; } while (!dir.empty()) { printf("%c", name[dir.top()]); dir.pop(); } }