#include <bits/stdc++.h>
using namespace std;
const int NMAX = 500000;
struct edge {
  int from, to, st, ed;
};
vector<edge> edges;
struct event {
  int t, id;
  bool add;
  bool operator<(const event& rhs) const {
    if (t != rhs.t) return t < rhs.t;
    if (add != rhs.add) return add;
    return id < rhs.id;
  }
  bool operator>(const event& rhs) const { return rhs < (*this); }
};
int dp[NMAX * 4 + 1];
int last[NMAX * 4 + 1];
vector<int> pending[NMAX * 2];
multiset<int> times[NMAX * 2 + 1];
int main() {
  int N, M;
  scanf("%d%d", &N, &M);
  for (int i = 0; i < M; i++) {
    int u, v, s, e;
    scanf("%d%d%d%d", &u, &v, &s, &e);
    u--, v--;
    for (int it = 0; it < 2; it++, swap(u, v)) {
      for (int dt = 0; dt < 2; dt++) {
        int st = s + dt;
        if (st < e) {
          if (st & 1)
            edges.push_back({u + N, v, st, e});
          else
            edges.push_back({u, v + N, st, e});
        }
      }
    }
  }
  edges.push_back({N + N, 0, -1, 0});
  priority_queue<event, vector<event>, greater<event>> pq;
  M = edges.size();
  for (int i = 0; i < M; i++) {
    const edge& e = edges[i];
    pq.push({e.st, i, true});
  }
  times[N + N].insert(-1);
  const int INF = 0x3fFFffFF;
  for (int i = 0; i < M; i++) dp[i] = INF;
  while (!pq.empty()) {
    const auto ev = pq.top();
    pq.pop();
    const auto& e = edges[ev.id];
    if (ev.add) {
      if (ev.t >= e.ed) continue;
      if (!times[e.from].empty()) {
        int t0 = *times[e.from].begin();
        if (t0 <= ev.t) {
          dp[ev.id] = min(dp[ev.id], ev.t);
          last[ev.id] = ev.t;
          times[e.to].insert(ev.t + 1);
          pq.push({e.ed, ev.id, false});
          for (const auto& p : pending[e.to]) pq.push({ev.t + 1, p, true});
          pending[e.to].clear();
        } else {
          pq.push({t0, ev.id, true});
        }
      } else {
        pending[e.from].push_back(ev.id);
      }
    } else {
      times[e.to].erase(times[e.to].find(last[ev.id] + 1));
    }
  }
  int ans = INF;
  for (int i = 0; i < M; i++)
    if (edges[i].to == N - 1 || edges[i].to == N + N - 1) ans = min(ans, dp[i]);
  printf("%d", ans < INF ? ans + 1 : -1);
}
