又是给一个迷宫找最短路径,不过不同的是要把路径输出
思路:先写一个正常的BFS,但是多加入一个数组,记录每个点的上一个点,到达最后一个点时再DFS向上搜索路径
#include<iostream> #include<queue> #include<string.h> using namespace std; typedef long long ll; typedef unsigned long long ull; int maze[5][5]; int d[5][5]; int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1}; pair<int, int> last[5][5]; void dfs(int x, int y){ if( x || y ) dfs(last[x][y].first, last[x][y].second); cout << "(" << x << ", " << y << ")" << endl; } void bfs(int x, int y){ queue< pair<int, int> > q; q.push(pair<int, int>(x, y)); d[x][y] = 0; while( !q.empty() ){ pair<int, int> t = q.front(); q.pop(); if(t.first == 4 && t.second == 4){ dfs(last[t.first][t.second].first, last[t.first][t.second].second); cout << "(" << t.first << ", " << t.second << ")" << endl; return; } for(int i=0; i<4; i++){ int nx = t.first + dx[i]; int ny = t.second + dy[i]; if(nx >= 0 && nx < 5 && ny >= 0 && ny < 5 && d[nx][ny] == -1 && maze[nx][ny] != 1){ d[nx][ny] = d[t.first][t.second] + 1; last[nx][ny].first = t.first; last[nx][ny].second = t.second; q.push(pair<int, int>(nx, ny)); } } } } int main(){ ios::sync_with_stdio(false); for(int i=0; i<5; i++) for(int j=0; j<5; j++) cin >> maze[i][j]; memset(d, -1, sizeof d); for(int i=0; i<5; i++) for(int j=0; j<5; j++) last[i][j].first = last[i][j].second = -1; bfs(0, 0); return 0; }