#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
const int MAXN = 500000;
const int MAXM = 500000;
int n, m;
int eto[2 * MAXM], el[MAXM], er[MAXM];
vector<int> adj[MAXN];
int adjidx[MAXN][2];
int d[2 * MAXM][2];
priority_queue<pair<int, int> > q;
bool elcmp(const int &p, const int &q) { return el[p >> 1] < el[q >> 1]; }
int nxtwithpar(int t, int p) { return t % 2 == p ? t : t + 1; }
void input() {
  scanf("%d%d", &n, &m);
  for (int i = (0); i < (n); ++i) adj[i].clear();
  for (int i = (0); i < (m); ++i) {
    int a, b;
    scanf("%d%d%d%d", &a, &b, &el[i], &er[i]);
    --a, --b, --er[i];
    eto[2 * i + 0] = b, adj[a].push_back(2 * i + 0);
    eto[2 * i + 1] = a, adj[b].push_back(2 * i + 1);
  }
}
int solve() {
  for (int i = (0); i < (n); ++i) {
    sort(adj[i].begin(), adj[i].end(), elcmp);
    for (int p = (0); p < (2); ++p) adjidx[i][p] = 0;
  }
  for (int x = (0); x < (2 * m); ++x)
    for (int p = (0); p < (2); ++p) d[x][p] = INT_MAX;
  q = priority_queue<pair<int, int> >();
  for (int j = (0); j < (((int)(adj[0]).size())); ++j) {
    int x = adj[0][j];
    if (el[x >> 1] == 0) d[x][0] = 0, q.push(make_pair(-d[x][0], 2 * x + 0));
  }
  while (!q.empty()) {
    int t = -q.top().first, x = q.top().second / 2, p = q.top().second % 2;
    q.pop();
    if (t > d[x][p]) continue;
    int at = eto[x ^ 1], to = eto[x];
    {
      int nx = x ^ 1, np = 1 - p, nt = t + 1;
      if (t <= er[x >> 1]) {
        if (nt < d[nx][np])
          d[nx][np] = nt, q.push(make_pair(-d[nx][np], 2 * nx + np));
      }
    }
    while (adjidx[at][p] < ((int)(adj[at]).size())) {
      int nx = adj[at][adjidx[at][p]], np = p,
          nt = max(t, nxtwithpar(el[nx >> 1], np));
      if (nt <= er[nx >> 1]) {
        if (nt - 1 <= er[x >> 1]) {
          if (nt < d[nx][np])
            d[nx][np] = nt, q.push(make_pair(-d[nx][np], 2 * nx + np));
        }
        if (nt - 1 > er[x >> 1]) break;
      }
      ++adjidx[at][p];
    }
  }
  int ret = n == 1 ? 0 : INT_MAX;
  for (int j = (0); j < (((int)(adj[n - 1]).size())); ++j) {
    int x = adj[n - 1][j];
    for (int p = (0); p < (2); ++p) ret = min(ret, d[x][p]);
  }
  return ret == INT_MAX ? -1 : ret;
}
void run() {
  input();
  printf("%d\n", solve());
}
int main() {
  run();
  return 0;
}
