数据结构求迷宫的最短路径c++
时间: 2024-02-03 19:04:04 浏览: 25
以下是使用Dijkstra算法求解迷宫最短路径的C++代码示例:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
const int N = 1010, INF = 0x3f3f3f3f;
int n, m;
int g[N][N], dist[N];
bool st[N];
struct Node {
int d, u;
bool operator> (const Node& t) const {
return d > t.d;
}
};
void dijkstra() {
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
priority_queue<Node, vector<Node>, greater<Node>> heap; heap.push({0, 1});
while (heap.size()) {
auto t = heap.top();
heap.pop();
int u = t.u;
if (st[u]) continue;
st[u] = true;
for (int i = 1; i <= n; i++) {
if (g[u][i] != INF && dist[i] > dist[u] + g[u][i]) {
dist[i] = dist[u] + g[u][i];
heap.push({dist[i], i});
}
}
}
}
int main() {
cin >> n >> m;
memset(g, 0x3f, sizeof g);
while (m--) {
int a, b, c;
cin >> a >> b >> c;
g[a][b] = g[b][a] = min(g[a][b], c);
}
dijkstra();
if (dist[n] == INF) puts("-1");
else cout << dist[n] << endl;
return 0;
}
```