#include<bits/stdc++.h>
using namespace std;
const int N=309;
int n, m[N+9][N+9], mp[N+9][N+9], x, y, t, dx[]={0, 0, 1, -1}, dy[]={1, -1, 0, 0};
struct node {
int x, y;
};
void bfs() {
queue<node> q;
q.push({0,0});
if (mp[0][0] >= 0x3f3f3f3f) {
cout << 0;
return;
}
while (q.size()) {
int x=q.front().x, y=q.front().y;
q.pop();
for (int i=0; i<4; i++) {
int xx=x+dx[i], yy=y+dy[i];
if (xx < 0 || xx > 303 || y < 0 || y > 303) continue;
if ((mp[yy][xx] > m[y][x]+1) && m[yy][xx]>=0x3f3f3f3f) {
q.push({xx, yy}); cout << q.back().x << ' ' << q.back().y << endl;
m[yy][xx]=m[y][x]+1;
if (mp[yy][xx]>=0x3f3f3f3f) {
cout << m[yy][xx];
return;
}
}
}
}
cout << -1;
}
int main() {
for (int i=0; i<=303; i++) {
for (int j=0; j<=303; j++) {
m[i][j]=mp[i][j]=0x3f3f3f3f;
}
}
cin >> n;
for (int i=0; i<n; i++) {
cin >> x >> y >> t;
mp[y][x]=min(t, mp[y][x]);
for (int j=0; j<4; j++) {
int xx=x+dx[j], yy=y+dy[j];
if (xx < 0 || xx > 307 || y < 0 || y > 307) continue;
mp[yy][xx]=min(t, mp[yy][xx]);
}
}
m[0][0]=0;
bfs();
for (int i=0; i<n+3; i++) {
for (int j=0; j<n+3; j++) {
cout << m[i][j] << ' ';
} cout << endl;
} cout << endl;
return 0;
}
改成数组模拟就ac了,
#include<bits/stdc++.h>
using namespace std;
const int N=309;
int n, m[N+9][N+9], x, y, h, t, dx[]={0, 0, 1, -1}, dy[]={1, -1, 0, 0}, mp[N+9][N+9];
struct node {
int x, y;
} q[N*N+9999];
void bfs() {
h=0, t=1;
q[h].x = q[h].y = 0;
if(mp[0][0]==0x3f3f3f3f)
{
puts("0");
return;
}
while (h<t) {
int x=q[h].x, y=q[h++].y;
for (int i=0; i<4; i++) {
int xx=x+dx[i], yy=y+dy[i];
if (xx < 0 || xx > 307 || y < 0 || y > 307) continue;
if ((mp[yy][xx] > m[y][x]+1) && m[yy][xx]>=0x3f3f3f3f) {
m[yy][xx]=m[y][x]+1;
q[t].y = yy; q[t++].x = xx;
if (mp[yy][xx]>=0x3f3f3f3f) {
cout << m[yy][xx];
return;
}
}
}
}
cout << -1;
}
int main() {
for (int i=0; i<N-2; i++) {
for (int j=0; j<N-2; j++) {
m[i][j]=mp[i][j]=0x3f3f3f3f;
}
}
cin >> n;
for (int i=0; i<n; i++) {
cin >> x >> y >> t;
mp[y][x]=min(t, mp[y][x]);
for (int j=0; j<4; j++) {
int xx=x+dx[j], yy=y+dy[j];
if (xx < 0 || xx > 303 || y < 0 || y > 303) continue;
mp[yy][xx]=min(t, mp[yy][xx]);
}
}
m[0][0]=0;
bfs();
return 0;
}