#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define fi first
#define sc second
#define sz(v) (int)v.size()
const int MAXN = 1e5+5, MAXM = 2*1e5+5;
const ll INF = 1e15;
vector<int> adj[MAXN], c[MAXN], p[MAXN];
map<int, ll> dist[MAXN];
int qtd[MAXM];
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int n,m; cin>>n>>m;
for(int i = 1; i <= m; i++){
int a,b,x,y; cin>>a>>b>>x>>y;
adj[a].push_back(b); c[a].push_back(x); p[a].push_back(y);
adj[b].push_back(a); c[b].push_back(x); p[b].push_back(y);
}
for(int i = 1; i <= n; i++){
dist[i][0] = INF;
for(int j = 0; j < sz(c[i]); j++ )dist[i][ c[i][j] ] = INF;
}
set< pair<ll, pair<int,int> > > st;
dist[1][0] = 0; st.insert( {0, {1,0} } );
ll ans = INF;
while(!st.empty()){
int v = st.begin()->sc.fi, a = st.begin()->sc.sc; st.erase(st.begin());
ll d = dist[v][a];
if(v == n)ans = min(ans, d );
for(int x : c[v]) qtd[x]++;
if(a > 0)qtd[ a ]--;
for(int i = 0; i < sz(adj[v]); i++){
int viz = adj[v][i], cor = c[v][i]; ll preco = p[v][i];
if(qtd[ cor ] <= 1){
ll d0 = dist[viz][0];
if(d0 > d){
st.erase( {d0, {viz, 0} } );
dist[viz][0] = d;
st.insert( {d, {viz, 0} } );
}
}
ll dcor = dist[viz][cor];
if(preco > 0 && dcor > d + preco){
st.erase( {dcor, {viz, cor} } );
dist[viz][cor] = d + preco;
st.insert( {d + preco, {viz, cor} } );
}
}
for(int x : c[v]) qtd[x] = 0;
}
if(ans == INF)cout<<"-1\n";
else cout<<ans<<"\n";
}