#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 7;
int n, m, ans, l[N], r[N], tp[N];
vector<int> v[N];
struct edge {
  int u, t, l, r;
} e[N];
struct note {
  int l, r, t;
};
inline bool operator<(note a, note b) { return a.l > b.l; }
priority_queue<note> f;
inline int read() {
  int num = 0;
  char g = getchar();
  while (g < 48 || 57 < g) g = getchar();
  while (47 < g && g < 58)
    num = (num << 1) + (num << 3) + g - 48, g = getchar();
  return num;
}
inline bool cmp(edge a, edge b) { return a.l < b.l; }
inline void update(int u, int l, int r) {
  if (l > r) return;
  if (u == n || u == n + n) ans = min(ans, l);
  note w;
  w.l = l, w.r = r, w.t = u, f.push(w);
}
inline int getres(int a, int b) {
  if ((a & 1) == (b & 1)) return b;
  return b - 1;
}
inline int getreq(int a, int b) {
  if ((a & 1) == (b & 1)) return b;
  return b + 1;
}
inline int solve(int u, int t) {
  int x;
  if (e[t].u == u || e[t].u + n == u)
    x = e[t].t;
  else
    x = e[t].u;
  if (u <= n) x += n;
  return x;
}
int main() {
  n = read(), m = read(), ans = 1234567890;
  for (int i = 1; i <= m; i++)
    e[i].u = read(), e[i].t = read(), e[i].l = read(), e[i].r = read() - 1;
  sort(e + 1, e + m + 1, cmp);
  for (int i = 1; i <= m; i++)
    v[e[i].u].push_back(i), v[e[i].t].push_back(i), v[e[i].u + n].push_back(i),
        v[e[i].t + n].push_back(i);
  update(1, 0, 0);
  while (f.size()) {
    note c = f.top();
    if (tp[c.t] == v[c.t].size())
      f.pop();
    else if (c.r < e[v[c.t][tp[c.t]]].l)
      f.pop();
    else if (c.l > e[v[c.t][tp[c.t]]].r)
      tp[c.t]++;
    else if (c.l <= e[v[c.t][tp[c.t]]].r)
      update(solve(c.t, v[c.t][tp[c.t]]),
             max(c.l, getreq(c.l, e[v[c.t][tp[c.t]]].l)) + 1,
             getres(c.l, e[v[c.t][tp[c.t]]].r) + 1),
          tp[c.t]++;
  }
  if (ans == 1234567890)
    cout << -1 << endl;
  else
    cout << ans << endl;
  return 0;
}
