#include <bits/stdc++.h>
using namespace std;
template <typename T1, typename T2>
bool Max(T1& a, T2 b) {
  return a < b ? a = b, 1 : 0;
}
template <typename T1, typename T2>
bool Min(T1& a, T2 b) {
  return a > b ? a = b, 1 : 0;
}
const int N = 500000;
vector<pair<pair<int, int>, int>> g[N];
int nt[N][2];
void solve() {
  int n, m, u, v, l, r;
  cin >> n >> m;
  while (m--) {
    cin >> u >> v >> l >> r;
    u--, v--;
    g[u].emplace_back(pair<int, int>(l, r), v);
    g[v].emplace_back(pair<int, int>(l, r), u);
  }
  for (int i = 0; i < (n); ++i)
    if (g[i].size()) sort(g[i].begin(), g[i].end());
  priority_queue<pair<pair<int, int>, int>, vector<pair<pair<int, int>, int>>,
                 greater<pair<pair<int, int>, int>>>
      q;
  q.emplace(pair<int, int>(0, 0), 0);
  while (q.size()) {
    auto cur = q.top();
    q.pop();
    int l = cur.first.first, r = cur.first.second, i = cur.second;
    if (i == n - 1) {
      cout << l << '\n';
      return;
    }
    bool c = l & 1;
    for (int& p = nt[i][c]; p < g[i].size(); p++) {
      if (g[i][p].first.first > r) break;
      Max(r, g[i][p].first.second);
      if ((r & 1) != c) r--;
      int nl = max(l, g[i][p].first.first) + 1;
      int nr = min(g[i][p].first.second, r + 1);
      if ((nl & 1) == c) nl++;
      if ((nr & 1) == c) nr--;
      if (nr >= nl) {
        q.emplace(pair<int, int>(nl, nr), g[i][p].second);
      }
    }
  }
  cout << -1 << '\n';
}
void init() {}
int main(void) {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.setf(ios::fixed);
  cout.precision(20);
  init();
  int TC = 1;
  for (int TI = 1; TI <= (TC); ++TI) {
    solve();
  }
  return 0;
}
