diff --git "a/problems/kamacoder/0126.\351\252\221\345\243\253\347\232\204\346\224\273\345\207\273astar.md" "b/problems/kamacoder/0126.\351\252\221\345\243\253\347\232\204\346\224\273\345\207\273astar.md" index 6ea6ca8346..0743c142fc 100644 --- "a/problems/kamacoder/0126.\351\252\221\345\243\253\347\232\204\346\224\273\345\207\273astar.md" +++ "b/problems/kamacoder/0126.\351\252\221\345\243\253\347\232\204\346\224\273\345\207\273astar.md" @@ -333,6 +333,70 @@ IDA * 算法 对这一空间增长问题进行了优化,关于 IDA * 算法, ## 其他语言版本 +### C++ 其他写法 +```C++ +// 懒人写法 +#include +#include +#include +using namespace std; +int b1, b2; +int dir[8][2] = { + -1, -2, -2, -1, 1, -2, -2, 1, -1, 2, 2, -1, 1, 2, 2, 1 +}; +struct Knight { + int x, y; + int fromStart; // 开始到当前坐标的距离 + int toEnd; // 当前坐标到目标坐标的距离 + int total; // 总距离 + int cnt; // 把计数放在Knight里面,一边计算距离一边计数就省了申请矩阵的空间了 + + bool operator < (const Knight& k) const { + return k.total < total; // 在priority_queue里用的比较符号 + } +}; +int Heuristic(const Knight& k) { + return (k.x - b1) * (k.x - b1) + (k.y - b2) * (k.y - b2); +} +int astart(const Knight& k) { + priority_queue que; // 把queue在这里申请就省了删掉里面的元素的麻烦 + int res; // 把结果存这里然后返回,直接打印出来 + que.push(k); + Knight cur, next; + while (!que.empty()) { + cur = que.top(); que.pop(); + if (cur.x == b1 && cur.y == b2) { res = cur.cnt; break; } // 保存找到的节点的步数用作返回 + + for (int i = 0; i < 8; i++) { + next.x = cur.x + dir[i][0], next.y = cur.y + dir[i][1]; + if (next.x < 1 || next.x > 1000 || next.y < 1 || next.y > 1000) continue; // 超标的不需要考虑 + + next.fromStart = cur.fromStart + 5; + next.toEnd = Heuristic(next); + next.total = next.fromStart + next.toEnd; + next.cnt = cur.cnt + 1; // 下一个点的步数是当前点的步数+1 + que.push(next); + } + } + return res; +} +int main() { + int n, a1, a2; cin >> n; + + for (int i = 0; i < n; i++) { + cin >> a1 >> a2 >> b1 >> b2; + Knight start; start.x = a1, start.y = a2; + start.fromStart = 0, start.toEnd = Heuristic(start); + start.total = start.fromStart + start.toEnd, start.cnt = 0; + + int res = astart(start); + cout << res << endl; + } + + return 0; +} +``` + ### Java ### Python