#include <bits/stdc++.h>
#define N 200005

using namespace std;

vector <int> adj[2][N];

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n, m, a, b, t, u, v;
	cin >> n >> m;
	vector<int> distance(n + 1, 0);
	vector<bool> visited(n + 1, false);
	for (int i = 0; i < m; i++)
	{
		cin >> a >> b >> t;
		adj[t][a].push_back(b);
		adj[t][b].push_back(a);
	}
	queue<int> q[2];
	cin >> u >> v;
	for (auto x : adj[0][u])
		q[0].push(x);
	for (auto x : adj[1][u])
		q[1].push(x);
	int p = 0;
	while (!visited[v]&&!(q[0].empty()&&q[1].empty()))
	{
		while (!q[p%2].empty())
		{
			int x = q[p%2].front();
			q[p%2].pop();
			if (!visited[x])
			{
				distance[x] = p;
				visited[x] = true;
				for (auto y : adj[0][x])
					if(!visited[y])
						q[0].push(y);
				for (auto y : adj[1][x])
					if(!visited[y])
						q[1].push(y);
			}
		}
		p++;
	}
	if (!visited[v])
		cout << -1 << endl;
	else
		cout << distance[v] << endl;
}