- 用优先队列实现
- 从起点出发,需要知道终点的坐标,根据起点和终点的距离进行预估
#include <iostream>
#include <queue>
#include <cmath>
using namespace std;
struct node {
int x, y;
int step;
double dis;
bool operator< (const node &b) const {
return this->step + this->dis > b.step + b.dis;
}
};
int n, m;
int sx, sy;
int ex, ey;
int mark[101][101][2];
int cnt;
int dir[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, 1, 1, -1, -1, 1, -1, -1};
char mmap[105][105];
double cal(int x, int y)
{
int a = ex - x, b = ey - y;
return sqrt(a * a + b * b);
}
void func(int x, int y)
{
if ('S' == mmap[x][y]) return ;
mmap[x][y] = '*';
func(mark[x][y][0], mark[x][y][1]);
}
void print()
{
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
cout << mmap[i][j];
if ('x' == mmap[i][j])
mmap[i][j] = '&';
}
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) {
cin >> mmap[i][j];
if ('S' == mmap[i][j])
sx = i, sy = j;
if ('T' == mmap[i][j])
ex = i, ey = j;
}
priority_queue<node> que;
que.push((node){sx, sy, 0, cal(sx, sy)});
while (!que.empty()) {
node tmp = que.top();
que.pop();
for (int i = 0; i < 8; ++i) {
int x = tmp.x + dir[i][0], y = tmp.y + dir[i][1];
if ('T' == mmap[x][y]) {
func(tmp.x, tmp.y);
print();
cout << ++tmp.step << endl;
return 0;
}
if ('.' == mmap[x][y]) {
mark[x][y][0] = tmp.x, mark[x][y][1] = tmp.y;
que.push((node){x, y, tmp.step + 1, cal(x, y)});
mmap[x][y] = 'x';
++cnt;
}
}
}
cout << "Cant not go to end" << endl;
return 0;
}