Floyd 算法精讲
Floyd 算法代码很简单,但真正理解起原理 还是需要花点功夫,大家在看代码的时候,会发现 Floyd 的代码很简单,甚至看一眼就背下来了,但我为了讲清楚原理,本篇还是花了大篇幅来讲解。
#include <iostream>
#include <vector>
#include <list>
using namespace std;
int main() {
int n, m, v1, v2, val;
cin >> n >> m;
vector<vector<vector<int>>>grid(n + 1, vector<vector<int>>(n + 1, vector<int>(n + 1, 10005)));
for (int i = 0; i < m; i++) {
cin >> v1 >> v2 >> val;
grid[v1][v2][0] = val;
grid[v2][v1][0] = val;
}
for (int k = 1; k <= n; k++) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
grid[i][j][k] = min(grid[i][j][k - 1], grid[i][k][k - 1] + grid[k][j][k - 1]);
}
}
}
int z, start, end;
cin >> z;
while (z--) {
cin >> start >> end;
if (grid[start][end][n] == 10005)cout << -1 << endl;
else cout << grid[start][end][n] << endl;
}
}
总结
算是又对dp有更深的理解了。
A * 算法精讲 (A star算法)
一般 笔试或者 面试的时候,不会考察A*, 都是会结合具体业务场景问 A*算法,例如:地图导航,游戏开发 等等。
其实基础版的A* 并不难,所以大家不要畏惧,理解本篇内容,甚至独立写出代码,大家可以做到,加油
#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
int moves[1001][1001];
int dire[8][2] = { -2,-1,-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2 };
int b1, b2;
struct Knight {
int x, y;
int g, h, f;
bool operator <(const Knight& k)const {
return k.f < f;
}
};
priority_queue<Knight>que;
int Heuristic(const Knight& k) {
return (k.x - b1) * (k.x - b1) + (k.y - b2) * (k.y - b2);
}
void aStar(const Knight& k) {
Knight cur, next;
que.push(k);
while (!que.empty()) {
cur = que.top(); que.pop();
if (cur.x == b1 && cur.y == b2)break;
for (int i = 0; i < 8; i++) {
next.x = cur.x + dire[i][0];
next.y = cur.y + dire[i][1];
if (next.x < 1 || next.x>1000 || next.y < 1 || next.y>1000)continue;
if (!moves[next.x][next.y]) {
moves[next.x][next.y] = moves[cur.x][cur.y] + 1;
next.g = cur.g + 5;
next.h = Heuristic(next);
next.f = next.g + next.h;
que.push(next);
}
}
}
}
int main() {
int n, a1, a2;
cin >> n;
while (n--) {
cin >> a1 >> a2 >> b1 >> b2;
memset(moves, 0, sizeof(moves));
Knight start;
start.x = a1;
start.y = a2;
start.g = 0;
start.h = Heuristic(start);
start.f = start.g + start.h;
aStar(start);
while (!que.empty())que.pop();
cout << moves[b1][b2] << endl;
}
return 0;
}
最短路算法总结篇
最各个最短路算法有个全面的了解