#include <bits/stdc++.h>
using namespace std;
class edge {
 public:
  int s, e, l, r;
  edge(int s1 = 0, int e1 = 0, int l1 = 0, int r1 = 0) {
    s = s1, e = e1, l = l1, r = r1;
  }
  bool operator<(const edge &t) const { return l > t.l; }
} E[2000010];
vector<edge> g[1000010];
int n, m, s[500010], e[500010], l[500010], r[500010];
priority_queue<edge> q;
int L[1000010];
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; i++)
    scanf("%d%d%d%d", &s[i], &e[i], &l[i], &r[i]), r[i]--;
  if (n == 1) {
    puts("0");
    return 0;
  }
  for (int i = 1; i <= m; i++) {
    E[i * 4 - 3] = edge(s[i] * 2 - 1, e[i] * 2, l[i] + (l[i] % 2 == 0),
                        r[i] - (r[i] % 2 == 0));
    E[i * 4 - 2] =
        edge(e[i] * 2, s[i] * 2 - 1, l[i] + l[i] % 2, r[i] - r[i] % 2);
    E[i * 4 - 1] =
        edge(s[i] * 2, e[i] * 2 - 1, l[i] + l[i] % 2, r[i] - r[i] % 2);
    E[i * 4] = edge(e[i] * 2 - 1, s[i] * 2, l[i] + (l[i] % 2 == 0),
                    r[i] - (r[i] % 2 == 0));
  }
  for (int i = 1; i <= m * 4; i++) q.push(E[i]);
  memset(L, 255, sizeof(L));
  L[2] = 0;
  while (!q.empty()) {
    edge fr = q.top();
    q.pop();
    if (fr.l > fr.r) continue;
    if (L[fr.s] >= fr.l) {
      if (fr.e == n * 2 || fr.e == n * 2 - 1) {
        printf("%d\n", fr.l + 1);
        return 0;
      }
      L[fr.e] = max(L[fr.e], fr.r + 1);
      for (edge x : g[fr.e]) {
        edge tmp = x;
        tmp.l = fr.l + 1;
        q.push(tmp);
      }
      g[fr.e].clear();
    } else
      g[fr.s].push_back(fr);
  }
  puts("-1");
  return 0;
}
