from scipy.sparse import*
n,*t=map(int,open(0).read().split())
*u,=range(1,n+1)
a=csgraph.dijkstra(csr_matrix((t[3::3]+[0]*~-n,(t[1::3]+u[1:],t[2::3]+u[:-1])),[n+1]*2),1,(1))[n]
print(int(a)if a<1e18else-1)