Uncle_hing @ 2024-04-07 16:48:12
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
int m,t[1010],step[310][310];
PII star[50010];
queue<PII> q;
int dx[] = {0,0,-1,1};
int dy[] = {1,-1,0,0};
bool checkMove(int x,int y,int curTime)//检查是否可以移动到(x,y),curTime为当前时刻
{
if(x < 0 || y < 0 || step[x][y] != -1) return false;
for(int i = 1;i <= m;i++)
{
if(abs(x - star[i].first) <= 1 && y == star[i].second && curTime >= t[i]) return false;
if(abs(y - star[i].second) <= 1 && x == star[i].first && curTime >= t[i]) return false;
}
return true;
}
bool checkSec(int x,int y)//检查是否安全
{
for(int i = 1;i <= m;i++)
{
if(abs(x - star[i].first) <= 1 && y == star[i].second) return false;
if(abs(y - star[i].second) <= 1 && x == star[i].first) return false;
}
return true;
}
int main()
{
cin >> m;
for(int i = 1;i <= m;i++)
{
cin >> star[i].first >> star[i].second >> t[i];
}
//bfs
memset(step,-1,sizeof(step));
q.push({0,0});
step[0][0] = 0;
while(!q.empty())
{
PII b = q.front();
q.pop();
for(int i = 0;i < 4;i++)
{
PII a = b;
a.first += dx[i];
a.second += dy[i];
if(checkMove(a.first,a.second,step[b.first][b.second] + 1))
{
q.push(a);
step[a.first][a.second] = step[b.first][b.second] + 1;
if(checkSec(a.first,a.second))
{
cout << step[a.first][a.second];
return 0;
}
}
}
}
cout << "-1";
return 0;
}