2个注意,
一个是优先级重写。利用,里面没有引用,然后是左大于右就排在后面。
bool operator<(mynode ne1, mynode ne2)
{
return ne1.cost > ne2.cost;
}
二是容器的元素每次都应该清除。
#include <iostream>
#include <cmath>
#include<set>
#include<string.h>
#include <queue>
#include <tuple>
#define scanf scanf_s
#define inf 0x3f3f3f3f
#define LL long long
#define mod 100000007
using namespace std;
struct mynode {
int cost, x, y;
};
bool operator<(mynode ne1, mynode ne2)//参数也可以为引用,值传递
{
return ne1.cost > ne2.cost;
}
int main() {
int m, n, T, cost, x, y;
int vis[104][104];
int way[][2] = { { 0, 1 },
{ 1, 0 },
{ -1, 0 },
{ 0, -1 } };
mynode zhu;
char c;
char A[105][105];
scanf("%d", &T);
while (T--) {
priority_queue<mynode> q;
memset(vis, 0, sizeof(vis));
int flag = 0;
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> A[i][j];
if (A[i][j] == '@') {
zhu = mynode{ 0, i, j };
vis[i][j] = 1;
}
}
}
for (q.push(zhu); !q.empty();q.pop()) {
mynode now = q.top();
cost = now.cost;
if (now.x <= 0 || n - 1 <= now.x || now.y <= 0 || m - 1 <= now.y) {
flag = 1;
cout << cost << endl;
break;
}
for (int i = 0; i < 4; i++) {
x = now.x; y = now.y;
x += way[i][0];
y += way[i][1];
if (!vis[x][y] && A[x][y] != '#') {
if (A[x][y] == '*') {
mynode a2 = mynode{ cost + 1,x,y };
vis[x][y] = 1;
q.push(a2);
}
else if(A[x][y]=='.'){
mynode a2 = mynode{ cost ,x,y };
vis[x][y] = 1;
q.push(a2);
}
}
}
}
if (!flag)puts("-1");
}
}