import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

N, M = map(int, input().split())
edge_d = np.array([input().split() for _ in range(M)], dtype=np.int64)
edge_n = np.vstack([np.arange(2, N + 1, dtype=np.int64),
                   np.arange(1, N, dtype=np.int64),
                   np.zeros(N - 1, dtype=np.int64)]).T
edge = np.concatenate([edge_d, edge_d[:, [1, 0, 2]], edge_n]).T

matr = csr_matrix((edge[2], (edge[:2] - 1)), (N, N))
ans = dijkstra(matr, indices=0)[-1]
if ans == np.inf:
    ans = -1
print(int(ans))
