xuanlv @ 2021-07-07 17:09:14
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <fstream>
const int N=50010;
const int M=310;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
typedef pair<int,int>PII;
int n;
int dist[M][M];
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
bool used_map[M][M];
int g[M][M];
bool is_safe(int x,int y)
{
if(x>=0&&x<=300&&y>=0&&y<=300&&used_map[x][y]==false)return true;
else return false;
}
bool st_ma[N];
int bfs(int x,int y){
queue<PII> q;
q.push({x,y});
memset(dist,-1,sizeof dist);
used_map[x][y]=true;
dist[x][y]=0;
while(!q.empty()){
auto t=q.front();
q.pop();
int t_x=t.first;
int t_y=t.second;
for(int i=0;i<4;i++){
int new_x=t_x+dx[i];
int new_y=t_y+dy[i];
if(is_safe(new_x,new_y)){
dist[new_x][new_y]=dist[t_x][t_y]+1;
if(dist[new_x][new_y]<g[new_x][new_y]){
used_map[new_x][new_y]=true;
if(g[new_x][new_y]==0x3f3f3f3f)return dist[new_x][new_y];
else q.push({new_x,new_y});
}
}
}
}
return -1;
}
int main(int argc, char** argv) {
cin>>n;
memset(g,0x3f,sizeof g);
for(int i=0;i<n;i++){
int x,y,t;
cin>>x>>y>>t;
g[x][y]=min(g[x][y],t);
for(int j=0;j<4;j++){
int n_x=x+dx[j];
int n_y=y+dy[j];
if(n_x>=0&&n_x<=300&&n_y>=0&&n_y<=300)g[n_x][n_y]=min(g[n_x][n_y],t);
}
}
cout<<bfs(0,0)<<endl;
return 0;
}