C++ A* code
时间: 2023-09-28 12:10:12 浏览: 48
Sure, below is a sample implementation of the A* algorithm in C++:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
struct Node {
int x, y;
int g, h;
Node* parent;
Node(int x, int y, int g, int h, Node* parent = nullptr) : x(x), y(y), g(g), h(h), parent(parent) {}
int f() const { return g + h; }
};
struct CompareNode {
bool operator()(Node* a, Node* b) const {
return a->f() > b->f();
}
};
vector<Node*> a_star(vector<vector<int>>& grid, int start_x, int start_y, int end_x, int end_y) {
int n = grid.size();
int m = grid[0].size();
priority_queue<Node*, vector<Node*>, CompareNode> open_list;
vector<vector<bool>> closed_list(n, vector<bool>(m, false));
Node* start = new Node(start_x, start_y, 0, abs(end_x - start_x) + abs(end_y - start_y));
open_list.push(start);
while (!open_list.empty()) {
Node* current = open_list.top();
open_list.pop();
if (current->x == end_x && current->y == end_y) {
vector<Node*> path;
while (current) {
path.push_back(current);
current = current->parent;
}
reverse(path.begin(), path.end());
return path;
}
closed_list[current->x][current->y] = true;
int dx[4] = { 1, -1, 0, 0 };
int dy[4] = { 0, 0, 1, -1 };
for (int i = 0; i < 4; i++) {
int new_x = current->x + dx[i];
int new_y = current->y + dy[i];
if (new_x < 0 || new_x >= n || new_y < 0 || new_y >= m || grid[new_x][new_y] == 1 || closed_list[new_x][new_y]) {
continue;
}
int new_g = current->g + 1;
int new_h = abs(end_x - new_x) + abs(end_y - new_y);
Node* neighbor = new Node(new_x, new_y, new_g, new_h, current);
open_list.push(neighbor);
}
}
return {};
}
int main() {
vector<vector<int>> grid = { {0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 0, 0},
{0, 1, 1, 0, 0},
{0, 0, 0, 0, 0} };
vector<Node*> path = a_star(grid, 0, 0, 4, 4);
for (auto node : path) {
cout << "(" << node->x << ", " << node->y << ")" << endl;
}
return 0;
}
```
The above code is just a sample implementation of the A* algorithm. You can modify it as per your needs.
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)