#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const long long nmax = 500005;
long long n, m, oddpt[nmax], evenpt[nmax];
struct edge {
  long long to, l, r;
  friend bool operator<(edge A, edge B) { return A.l < B.l; }
};
vector<edge> nod[nmax];
struct event {
  long long start, ending, to, par;
  friend bool operator<(event A, event B) { return A.start > B.start; }
};
priority_queue<event> pq;
int32_t main() {
  cin >> n >> m;
  for (long long i = 1; i <= m; i++) {
    long long a, b, l, r;
    cin >> a >> b >> l >> r;
    nod[a].push_back({b, l, r});
    nod[b].push_back({a, l, r});
  }
  for (long long i = 1; i <= n; i++) {
    sort((nod[i]).begin(), (nod[i]).end());
  }
  pq.push({0, 0, 1, 0});
  while (pq.size()) {
    auto it = pq.top();
    pq.pop();
    if (it.to == n) {
      return cout << it.start, 0;
    } else {
      if (it.par == 0) {
        for (long long i = evenpt[it.to]; i < (long long)nod[it.to].size();
             i++) {
          if (nod[it.to][i].l > it.ending) {
            break;
          }
          if (it.ending >= nod[it.to][i].l && it.start < nod[it.to][i].r) {
            long long start = max(it.start + 1, nod[it.to][i].l + 1);
            if (start % 2 == 0) start++;
            long long ending = nod[it.to][i].r;
            if (ending % 2 == 0) ending--;
            if (start <= ending) {
              pq.push({start, ending, nod[it.to][i].to, 1 - it.par});
            }
          }
          evenpt[it.to]++;
        }
      } else {
        for (long long i = oddpt[it.to]; i < (long long)nod[it.to].size();
             i++) {
          if (nod[it.to][i].l > it.ending) {
            break;
          }
          if (it.ending >= nod[it.to][i].l && it.start < nod[it.to][i].r) {
            long long start = max(it.start + 1, nod[it.to][i].l + 1);
            if (start % 2 == 1) start++;
            long long ending = nod[it.to][i].r;
            if (ending % 2 == 1) ending--;
            if (start <= ending) {
              pq.push({start, ending, nod[it.to][i].to, 1 - it.par});
            }
          }
          oddpt[it.to]++;
        }
      }
    }
  }
  return cout << -1, 0;
}
