#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<queue>
#define nn 50010
#define mm 200010
using namespace std;
bool vis[nn];
deque<int> q;
int e=0,ee=0,mb=-1,n,m;
int fir[nn],nxt[mm],dis[nn],to[mm],w[mm];
struct bb{
int fro,to,a,b;
}b[mm];
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();}
while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();}
return x*f;
}
void add(int u,int v,int ww)
{
nxt[++e]=fir[u];fir[u]=e;to[e]=v;w[e]=ww;
}
int bfs()
{
int o;
while(!q.empty())
{
o=q.front();q.pop_front();
for(int i=fir[o];i;i=nxt[i])
if(dis[to[i]]>max(dis[o],w[i]))
{
dis[to[i]]=max(dis[o],w[i]);
if(!vis[to[i]])
{
vis[to[i]]=1;
if(q.empty()||dis[q.front()]<dis[to[i]])
q.push_back(to[i]);
else
q.push_front(to[i]);
}
}
vis[o]=0; ////////////////
}
return dis[n];
}
int cmp(const bb&i,const bb&j)
{
return i.a<j.a;
}
int main()
{
// freopen("forest.in","r",stdin);
// freopen("forest.out","w",stdout);
int ma=-1,mi=500000,u,v,aa,bb,ans=1000001,zc,now=1;
n=read();m=read();
for(int i=1;i<=m;i++)
{
u=read();v=read();aa=read();bb=read();
b[++ee].fro=u;b[ee].to=v;b[ee].a=aa;b[ee].b=bb;
b[++ee].fro=v;b[ee].to=u;b[ee].a=aa;b[ee].b=bb;
ma=max(ma,aa);
mi=min(mi,aa);
}
q.push_back(1);
sort(b+1,b+ee+1,cmp);
fill(dis,dis+n+1,1000001);
vis[1]=1;
dis[1]=0;
for(int i=mi;i<=ma;i++)
if(b[now].a==i)
{
while(b[now].a==i)
{
add(b[now].fro,b[now].to,b[now].b);
q.push_back(b[now].fro);
q.push_back(b[now].to);
now++;
}
zc=bfs();
if(zc+i<ans)
ans=zc+i;
}
if(ans<1000001)
printf("%d",ans);
else
printf("-1");
return 0;
}