#include <bits/stdc++.h>
using namespace std;
const int N = 500005;
const int inf = 2000000000;
struct node {
  int t, l, r;
  node() {}
  node(int t, int l, int r) : t(t), l(l), r(r) {}
  friend bool operator<(node a, node b) { return a.l < b.l; }
} w;
struct P {
  int x, y;
  P() {}
  P(int x, int y) : x(x), y(y) {}
  friend bool operator<(P a, P b) { return a.y > b.y; }
} k, u;
int n, m, x, y, l, r, ans;
int st[N][2];
vector<node> lev[N][2];
priority_queue<P> q;
int dij() {
  int j, c, b, now, d;
  q.push(P(1, 0));
  while (!q.empty()) {
    k = q.top();
    q.pop();
    x = k.x;
    c = now = k.y;
    b = c & 1;
    if (x == n) return c;
    for (j = st[x][b]; j < lev[x][b].size(); j++) {
      w = lev[x][b][j];
      if (w.l > now) break;
      st[x][b] = j + 1;
      if (w.r < c) continue;
      now = max(now, w.r);
      if (now - b & 1) now--;
      d = max(w.l, c);
      if (d % 2 != b) d++;
      if (d + 1 <= w.r && d >= w.l) q.push(P(w.t, d + 1));
    }
  }
  return -1;
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d%d", &x, &y, &l, &r);
    for (int j = 0; j < 2; j++) {
      lev[x][j].push_back(node(y, l, r));
      lev[y][j].push_back(node(x, l, r));
    }
  }
  for (int i = 1; i <= n; i++)
    for (int j = 0; j < 2; j++) sort(lev[i][j].begin(), lev[i][j].end());
  ans = dij();
  printf("%d\n", ans);
  return 0;
}
