Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

添加C++懒人A*写法解“127.骑士的攻击” #2834

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
64 changes: 64 additions & 0 deletions problems/kamacoder/0126.骑士的攻击astar.md
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,70 @@ IDA * 算法 对这一空间增长问题进行了优化,关于 IDA * 算法,

## 其他语言版本

### C++ 其他写法
```C++
// 懒人写法
#include <iostream>
#include <vector>
#include <queue>
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<Knight> 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
Expand Down