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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include <iostream> #include <queue>
using namespace std;
struct Point { int x; int y;
Point() : x(0), y(0) {}
Point(int x, int y) : x(x), y(y) {} };
vector<vector<int>> directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
void findShortPath_BFS(vector<vector<int>> &maze, vector<vector<Point>> &pre, int startX, int startY, int endX, int endY) { queue<Point> q; q.push(Point(startX, startY)); maze[startX][startY] = 1; while (!q.empty()) { Point current = q.front(); q.pop(); if (current.x == endX && current.y == endY) { break; } for (auto direction:directions) { int currentX = current.x + direction[0]; int currentY = current.y + direction[1]; if (currentX >= 0 && currentX < maze.size() && currentY >= 0 && currentY < maze[0].size() && maze[currentX][currentY] == 0) { q.push(Point(currentX, currentY)); maze[currentX][currentY] = 1; pre[currentX][currentY] = current; } } } }
void print(Point point, vector<vector<Point>> &pre) { if (point.x == 0 && point.y == 0) { cout << point.x << " " << point.y << endl; return; } print(pre[point.x][point.y], pre); cout << point.x << " " << point.y << endl; }
int main() { vector<vector<int>> maze = {{0, 0, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 1, 0}, {1, 1, 0, 1, 1}, {0, 0, 0, 0, 0}}; vector<vector<Point>> pre(5, vector<Point>(5)); int startX = 0; int startY = 0; int endX = 4; int endY = 4; findShortPath_BFS(maze, pre, startX, startY, endX, endY); print(Point(endX, endY), pre); return 0; }
|