#include <bits/stdc++.h>
using namespace std;
const int N = (int)5e5 + 5;
struct Edge {
  int v, l, r;
  Edge() {}
  Edge(const int& _v, const int& _l, const int& _r) : v(_v), l(_l), r(_r) {}
  bool operator<(const Edge& other) const {
    if (l != other.l) return l < other.l;
    return r < other.r;
  }
};
vector<vector<Edge> > es;
vector<int> now;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  int n, m, a, b, l, r;
  cin >> n >> m;
  es.resize(n + n + 1);
  now.resize(n + n + 1);
  for (int i = 0; i < m; ++i) {
    cin >> a >> b >> l >> r;
    if (l & 1) {
      if (r & 1) {
        es[a].emplace_back(b + n, l + 1, r - 1);
        es[b].emplace_back(a + n, l + 1, r - 1);
        es[a + n].emplace_back(b, l, r - 2);
        es[b + n].emplace_back(a, l, r - 2);
      } else {
        if (l + 1 < r) {
          es[a].emplace_back(b + n, l + 1, r - 2);
          es[b].emplace_back(a + n, l + 1, r - 2);
        }
        es[a + n].emplace_back(b, l, r - 1);
        es[b + n].emplace_back(a, l, r - 1);
      }
    } else {
      if (r & 1) {
        es[a].emplace_back(b + n, l, r - 1);
        es[b].emplace_back(a + n, l, r - 1);
        if (l + 1 < r) {
          es[a + n].emplace_back(b, l + 1, r - 2);
          es[b + n].emplace_back(a, l + 1, r - 2);
        }
      } else {
        es[a].emplace_back(b + n, l, r - 2);
        es[b].emplace_back(a + n, l, r - 2);
        es[a + n].emplace_back(b, l + 1, r - 1);
        es[b + n].emplace_back(a, l + 1, r - 1);
      }
    }
  }
  for (int i = 1; i <= n + n; ++i) sort(es[i].begin(), es[i].end());
  priority_queue<tuple<int, int, int>, vector<tuple<int, int, int> >,
                 greater<tuple<int, int, int> > >
      q;
  q.emplace(0, 0, 1);
  int ans = 0x7f7f7f7f;
  while (!q.empty()) {
    int u, b, e;
    tie(b, e, u) = q.top();
    q.pop();
    if (u == n || u == n + n) ans = min(ans, b);
    for (int& i = now[u]; i < (int)es[u].size(); ++i) {
      if (e < es[u][i].l) break;
      if (b <= es[u][i].r)
        q.emplace(max(b + 1, es[u][i].l + 1), es[u][i].r + 1, es[u][i].v);
    }
  }
  cout << (ans == 0x7f7f7f7f ? -1 : ans) << '\n';
  return 0;
}
