#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 5, M = N << 2;
int n, m, Late[N][2], tot, H[N][2], nxt[M];
struct Data {
  int u, v, l, r;
} tmp, e[M];
priority_queue<Data> h;
bool operator<(Data a, Data b) { return a.l > b.l; }
char c;
int read() {
  int x = 0, sig = 1;
  for (c = getchar(); c < '0' || c > '9'; c = getchar())
    if (c == '-') sig = -1;
  for (; c >= '0' && c <= '9'; c = getchar()) x = x * 10 + c - 48;
  return x * sig;
}
void Add(Data t) {
  e[++tot] = t;
  nxt[tot] = H[t.u][t.l & 1];
  H[t.u][t.l & 1] = tot;
}
void Extend(int x, int t, int en) {
  Late[x][t & 1] = max(Late[x][t & 1], en);
  for (int i = H[x][t & 1]; i; i = nxt[i]) {
    tmp = e[i];
    tmp.l = t;
    h.push(tmp);
  }
  H[x][t & 1] = 0;
}
int main() {
  n = read();
  m = read();
  if (n == 1) {
    printf("0\n");
    return 0;
  }
  for (int a, b, l, r, i = 1; i <= m; i++) {
    a = read();
    b = read();
    l = read();
    r = read() - 1;
    tmp.u = a;
    tmp.v = b;
    tmp.l = l;
    tmp.r = r - ((r ^ l) & 1);
    h.push(tmp);
    tmp.l++;
    tmp.r = r - ((r ^ l ^ 1) & 1);
    h.push(tmp);
    swap(tmp.u, tmp.v);
    tmp.l = l;
    tmp.r = r - ((r ^ l) & 1);
    h.push(tmp);
    tmp.l++;
    tmp.r = r - ((r ^ l ^ 1) & 1);
    h.push(tmp);
  }
  memset(Late, 255, sizeof(Late));
  Late[1][0] = 0;
  for (; !h.empty();) {
    tmp = h.top();
    h.pop();
    if (tmp.l > tmp.r) continue;
    if (Late[tmp.u][tmp.l & 1] >= tmp.l) {
      if (tmp.v == n) {
        printf("%d\n", tmp.l + 1);
        return 0;
      }
      Extend(tmp.v, tmp.l + 1, tmp.r + 1);
    } else
      Add(tmp);
  }
  printf("-1\n");
  return 0;
}
