#include <bits/stdc++.h>
using namespace std;
int n, m, a, b, c, g[2005][2005];
int dis[2005];
bool vis[2005];
void dijk(int s)
{
memset(dis, 0x3f, sizeof(dis));
dis[s] = 0;
while (true)
{
int k = 0;
for (int i = 1; i <= n; i++)
if (!vis[i] && dis[k] > dis[i])
k = i;
if (k == 0)
break;
vis[k] = 1;
for (int i = 1; i <= n; i++)
{
if (!vis[i] && dis[i] > dis[k] + g[k][i])
{
dis[i] = dis[k] + g[k][i];
}
}
}
}
int main()
{
memset(g, 0x3f, sizeof(g));
cin >> n >> m;
while (m--)
{
cin >> a >> b >> c;
if (g[a][b] > c)
g[a][b] = g[b][a] = c;
}
for (int i = 1; i <= n; i++)
g[i][i] = 0;
dijk(1);
if (dis[n] == dis[0])
cout << -1;
else
cout << dis[n];
return 0;
}