#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
const int inf = 2e9;
int gi() {
  int x = 0, o = 1;
  char ch = getchar();
  while ((ch < '0' || ch > '9') && ch != '-') ch = getchar();
  if (ch == '-') o = -1, ch = getchar();
  while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
  return x * o;
}
int n, m, p[N][2];
vector<pair<int, int> > G[N][2];
vector<int> f[N][2];
struct data {
  int d, u, t, e;
  bool operator<(const data &A) const { return d > A.d; }
};
struct edge {
  int v, l, r, o;
};
vector<edge> E[N];
int main() {
  cin >> n >> m;
  if (n == 1) return puts("0"), 0;
  for (int i = 1, u, v, l, r; i <= m; i++)
    u = gi(), v = gi(), l = gi(), r = gi(),
    E[u].push_back((edge){v, l, r, int(E[v].size())}),
    E[v].push_back((edge){u, l, r, int(E[u].size()) - 1});
  for (int i = 1; i <= n; i++)
    for (int j = 0; j < 2; j++) {
      f[i][j].resize(int(E[i].size()), inf);
      G[i][j].resize(int(E[i].size()));
      for (int k = 0; k < int(E[i].size()); k++)
        G[i][j][k] = make_pair(E[i][k].l + ((E[i][k].l & 1) ^ j), k);
      sort(G[i][j].begin(), G[i][j].end());
    }
  priority_queue<data> Q;
  for (int i = 0; i < int(E[1].size()); i++)
    if (!E[1][i].l) f[1][0][i] = 0, Q.push((data){0, 1, 0, i});
  while (!Q.empty()) {
    data x = Q.top();
    Q.pop();
    int u = x.u, t = x.t, e = x.e, re = E[u][e].o, v = E[u][e].v,
        d = f[u][t][e], r = E[u][e].r - ((E[u][e].r & 1) ^ t);
    if (x.d > d) continue;
    if (f[v][t ^ 1][re] > d + 1 && E[v][re].l <= d + 1 && E[v][re].r >= d + 1)
      f[v][t ^ 1][re] = d + 1, Q.push((data){d + 1, v, t ^ 1, re});
    if (d > r) continue;
    while (p[u][t] < int(E[u].size())) {
      pair<int, int> g = G[u][t][p[u][t]];
      if (g.first > r) break;
      if (f[u][t][g.second] > max(g.first, d))
        f[u][t][g.second] = max(g.first, d),
        Q.push((data){max(g.first, d), u, t, g.second});
      ++p[u][t];
    }
  }
  int ans = inf;
  for (int i = 0; i < int(E[n].size()); i++)
    for (int j = 0; j < 2; j++) ans = min(ans, f[n][j][i]);
  if (ans == inf) ans = -1;
  cout << ans;
  return 0;
}
