#include <bits/stdc++.h>
using namespace std;
const int N = 2e6;
int n, m;
int L[N][2], R[N][2];
struct node {
  int a, b, l, r;
  friend bool operator<(node p1, node p2) { return p1.l > p2.l; }
};
priority_queue<node> q;
vector<node> a[N][2] = {};
int read(void) {
  int s = 0, w = 0;
  char c = getchar();
  while (c < '0' || c > '9') w |= c == '-', c = getchar();
  while (c >= '0' && c <= '9') s = s * 10 + c - 48, c = getchar();
  return w ? -s : s;
}
int main(void) {
  n = read(), m = read();
  for (int i = 1; i <= m; ++i) {
    int a = read(), b = read();
    int l = read(), r = read() - 1;
    int t = (l ^ r) & 1;
    q.push(node{a, b, l, r - t});
    q.push(node{b, a, l, r - t});
    t = t ^ 1;
    q.push(node{a, b, l + 1, r - t});
    q.push(node{b, a, l + 1, r - t});
  }
  memset(R, -1, sizeof R);
  memset(L, 30, sizeof L);
  L[1][0] = R[1][0] = 0;
  while (q.size()) {
    node now = q.top();
    q.pop();
    int x = now.a, y = now.b;
    int l = now.l, r = now.r;
    if (l > r)
      continue;
    else if (R[x][l % 2] < l)
      a[x][l % 2].push_back(now);
    else if (y == n)
      return cout << l + 1, 0;
    else {
      l = max(L[x][l % 2], l) + 1, r++;
      L[y][l % 2] = min(L[y][l % 2], l);
      R[y][l % 2] = max(R[y][l % 2], r);
      for (int i = 0; i < a[y][l % 2].size(); ++i)
        a[y][l % 2][i].l = l, q.push(a[y][l % 2][i]);
      a[y][l % 2].clear();
    }
  }
  cout << (n == 1 ? 0 : -1) << endl;
  return 0;
}
