#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e5 + 5;
struct edg {
  int u, v, l, r;
  edg(int u = 0, int v = 0, int l = 0, int r = 0) : u(u), v(v), l(l), r(r) {}
  bool operator<(const edg &n1) const { return l > n1.l; }
};
priority_queue<edg> q;
vector<edg> adj[maxn][2];
int n, m;
int dp[maxn][2];
inline void add(int u, int v, int l, int r) {
  int op = l % 2;
  if (dp[u][op] >= l) {
    if (v == n) {
      cout << l + 1 << endl;
      exit(0);
    }
    if (r + 1 > dp[v][op ^ 1]) {
      dp[v][op ^ 1] = r + 1;
      for (int i = 0; i < adj[v][op ^ 1].size(); i++) {
        edg t = adj[v][op ^ 1][i];
        if (l + 1 <= t.r) q.push(edg(v, t.v, l + 1, t.r));
      }
      adj[v][op ^ 1].clear();
    }
  } else {
    adj[u][op].push_back(edg(u, v, l, r));
  }
}
int main() {
  cin >> n >> m;
  memset(dp, 0xf3, sizeof(dp));
  dp[1][0] = 0;
  for (int i = 1; i <= m; i++) {
    int u, v, l, r;
    scanf("%d%d%d%d", &u, &v, &l, &r);
    if ((r - l + 1) % 2 == 0) {
      q.push(edg(u, v, l, r - 1));
      q.push(edg(v, u, l, r - 1));
      if (l + 1 <= r - 2) {
        q.push(edg(u, v, l + 1, r - 2));
        q.push(edg(v, u, l + 1, r - 2));
      }
    } else {
      if (l <= r - 2) {
        q.push(edg(u, v, l, r - 2));
        q.push(edg(v, u, l, r - 2));
      }
      q.push(edg(u, v, l + 1, r - 1));
      q.push(edg(v, u, l + 1, r - 1));
    }
  }
  if (n == 1) {
    cout << "0" << endl;
    return 0;
  }
  while (!q.empty()) {
    edg t = q.top();
    q.pop();
    add(t.u, t.v, t.l, t.r);
  }
  cout << "-1" << endl;
  return 0;
}
