#include <bits/stdc++.h>

typedef std::pair <int, int> pr;
typedef std::map <int, int> map;
const int N = 500054, M = 2000054, INF = 0x3f3f3f3f;

struct edge {
	int u, v, w;
	edge (int u0 = 0, int v0 = 0, int w0 = 0) : u(u0), v(v0), w(w0) {}
} e[M];

int n, m, V, E = 0;
int first[N], next[M];
int d[N];
map g[M];
std::priority_queue <pr, std::vector <pr>, std::greater <pr> > pq;

inline void addedge(int u, int v, int w1, int w2) {
	e[++E] = edge(u, v, w1), next[E] = first[u], first[u] = E;
	e[++E] = edge(v, u, w2), next[E] = first[v], first[v] = E;
}

inline int get(int ty, int id) {
	map::iterator it; bool ret;
	std::tie(it, ret) = g[ty].emplace(id, V + 1);
	return ret ? ++V : it->second;
}

void Dijkstra(int s) {
	int i, x, y, di;
	memset(d, 63, (V + 1) << 2);
	for (pq.emplace(d[s] = 0, s); !pq.empty(); ) {
		std::tie(di, x) = pq.top(), pq.pop();
		if (d[x] != di) continue;
		for (i = first[x]; i; i = next[i])
			if (di + e[i].w < d[y = e[i].v])
				pq.emplace(d[y] = di + e[i].w, y);
	}
}

int main() {
	int i, u, v, w;
	scanf("%d%d", &n, &m), V = n;
	for (i = 0; i < m; ++i)
		scanf("%d%d%d", &u, &v, &w), addedge(get(w, u), get(w, v), 0, 0);
	for (i = 0; i < M; ++i)
		for (const pr &p : g[i]) addedge(p.first, p.second, 1, 0);
	Dijkstra(1), printf("%d\n", d[n] >= INF ? -1 : d[n]);
	return 0;
}