#include <bits/stdc++.h>
using namespace std;
const int M = 500005;
int read() {
  int x = 0, f = 1;
  char c;
  while ((c = getchar()) < '0' || c > '9') {
    if (c == '-') f = -1;
  }
  while (c >= '0' && c <= '9') {
    x = (x << 3) + (x << 1) + (c ^ 48);
    c = getchar();
  }
  return x * f;
}
int n, m, f[M][2];
struct node {
  int u, v, l, r, op;
  node(int U = 0, int V = 0, int L = 0, int R = 0, int O = 0)
      : u(U), v(V), l(L), r(R), op(O) {}
  bool operator<(const node &b) const { return l > b.l; }
};
priority_queue<node> q;
vector<node> g[M][2];
void upd(int u, int v, int l, int r) {
  int op = l & 1;
  if (f[u][op] >= l) {
    if (v == n) {
      printf("%d\n", l + 1);
      exit(0);
    }
    if (f[v][!op] <= r + 1) {
      f[v][!op] = r + 1;
      for (node x : g[v][!op]) q.push(node(x.u, x.v, l + 1, x.r));
      g[v][!op].clear();
    }
  } else
    g[u][op].push_back(node(u, v, l, r));
}
signed main() {
  n = read();
  m = read();
  if (n == 1) {
    puts("0");
    exit(0);
  }
  for (int i = 1; i <= m; i++) {
    int u = read(), v = read(), l = read(), r = read() - 1;
    int op = (r - l) & 1;
    q.push(node(u, v, l, r - op, 1));
    q.push(node(u, v, l + 1, r - (!op), 1));
  }
  memset(f, -0x3f, sizeof f);
  f[1][0] = 0;
  while (!q.empty()) {
    node t = q.top();
    q.pop();
    if (t.l > t.r) continue;
    upd(t.u, t.v, t.l, t.r);
    if (t.op == 1) upd(t.v, t.u, t.l, t.r);
  }
  puts("-1");
}
