#include <bits/stdc++.h>
using namespace std;
const long long int MOD = 1000000007;
const long long int INF = 10000000000000007;
int main() {
  int n, m;
  cin >> n >> m;
  vector<vector<long long int> > cost(n + 1, vector<long long int>(n + 1, INF));
  for (int i = 0; i < n; i++) cost[i + 1][i] = 0;
  int a, b, c;
  for (int i = 0; i < m; i++) {
    cin >> a >> b >> c;
    cost[a][b] = c;
    cost[b][a] = c;
  }
  vector<long long int> d(n + 1, INF), used(n + 1, 0);
  d[1] = 0;
  while (true) {
    int v = -1;
    for (int i = 1; i <= n; i++) {
      if (!used[i] && (v == -1 || d[i] < d[v])) v = i;
    }
    if (v == -1) break;
    used[v] = true;
    for (int i = 1; i <= n; i++) {
      d[i] = min(d[i], d[v] + cost[v][i]);
    }
  }
  if (d[n] == INF)
    cout << -1;
  else
    cout << d[n];
  return 0;
}
