xjk15672261875 @ 2023-12-28 23:59:56
#include<stdio.h>
int book[310][310], book1[310][310], book2[310][310], nest[4][2] = { {0,1},{1,0},{-1,0},{0,-1} };
struct nb {
int x;
int y;
int s;
} a[90020];
int main()
{
int n, i, j;
scanf("%d", &n);
memset(book1, 100, sizeof(book1));
for (i = 1; i <= n; i++)
{
int g, k, h;
scanf("%d %d %d", &g,&k,&h);
if (book1[g][k] > h);
book1[g][k] = h;
book2[g][k] = 1;
for (j = 0; j <= 3; j++)
{
int tx = g + nest[j][0];
int ty = k + nest[j][1];
if (tx < 0 || tx>300 || ty < 0 || ty>300)
continue;
if (book1[tx][ty] > h)
book1[tx][ty] = h;
book2[tx][ty] = 1;
}
}
if (book2[0][0] == 0)
{
printf("0\n");
return 0;
}
int hard = 1, tail = 1;
a[tail].x = 0;
a[tail].y = 0;
a[tail].s = 0;
book[0][0] = 1;
tail++;
int flag = 0;
while (hard < tail)
{
for (i = 0; i <= 3; i++)
{
int tx = a[hard].x + nest[i][0];
int ty = a[hard].y + nest[i][1];
if (tx < 0 || tx>300 || ty < 0 || ty>300)
continue;
if (a[hard].s + 1 >= book1[tx][ty])
continue;
if (book[tx][ty] == 0)
{
a[tail].x = tx;
a[tail].y = ty;
a[tail].s = a[hard].s + 1;
book[tx][ty] = 1;
tail++;
}
if (book2[tx][ty] == 0)
{
flag = 1;
break;
}
}
if (flag == 1)
{
break;
}
hard++;
}
if (flag == 1)
printf("%d\n", a[tail - 1].s);
else
printf("-1\n");
return 0;
}