#include <bits/stdc++.h>
using namespace std;
vector<int> dijkstra(int v, map<int, map<int, int>> &g, int r) {
  vector<int> cost(v, 1 << 30);
  cost[r] = 0;
  priority_queue<pair<int, int>> pq;
  pq.push({0, r});
  while (!pq.empty()) {
    auto t = pq.top();
    pq.pop();
    if (cost[t.second] < -t.first) {
      continue;
    }
    for (auto x : g[t.second]) {
      if (cost[x.first] > cost[t.second] + g[t.second][x.first]) {
        cost[x.first] = cost[t.second] + g[t.second][x.first];
        pq.push({-cost[x.first], x.first});
      }
    }
  }
  return cost;
}
int main() {
  int n, m;
  cin >> n >> m;
  int l[m], r[m], c[m];
  for (long long i = (long long)(0); i < (long long)(m); ++i) {
    cin >> l[i] >> r[i] >> c[i];
    l[i]--;
    r[i]--;
  }
  map<int, map<int, int>> g;
  vector<int> p;
  for (long long i = (long long)(0); i < (long long)(m); ++i) {
    if (g[l[i]][r[i]] == 0) {
      g[l[i]][r[i]] = 1 << 30;
      g[r[i]][l[i]] = 1 << 30;
    }
    g[l[i]][r[i]] = min(c[i], g[l[i]][r[i]]);
    g[r[i]][l[i]] = min(c[i], g[r[i]][l[i]]);
    p.push_back(l[i]);
    p.push_back(r[i]);
  }
  sort(p.begin(), p.end());
  for (long long i = (long long)(0); i < (long long)(m); ++i) {
    auto itr = lower_bound(p.begin(), p.end(), r[i]) - p.begin();
    for (int ii = itr; ii >= 0 && p[ii] > l[i]; ii--) {
      if (g[r[i]][p[ii]] == 0) {
        g[r[i]][p[ii]] = 1 << 30;
        g[p[ii]][r[i]] = 1 << 30;
      }
      g[r[i]][p[ii]] = min(g[r[i]][p[ii]], c[i]);
      g[p[ii]][r[i]] = min(g[r[i]][p[ii]], c[i]);
    }
  }
  auto cost = dijkstra(n, g, 0);
  if (cost[n - 1] == 1 << 30) {
    cout << -1 << endl;
  } else {
    cout << cost[n - 1] << endl;
  }
  return 0;
}
