#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int shortest_path(vector<int> d, deque<int> q, int u, int v, const vector<vector<pair<int, int>>>& g, int m)
{
	d[u] = 0;
	q.push_front(u);

	while (!q.empty())
	{
		int tr = q.front(); q.pop_front();

		int l = g[tr].size();
		for (int i = 0; i < l; i++)
		{
			if (d[tr] + g[tr][i].second < d[g[tr][i].first])
			{
				d[g[tr][i].first] = d[tr] + g[tr][i].second;

				if (g[tr][i].second) q.push_back(g[tr][i].first);
				else q.push_front(g[tr][i].first);
			}
		}

	}

	if (d[v] == 3 * m) return -1;
	else return d[v];
}

int solve(vector<pair<int, int>> edges, vector<bool> edge_type, int n, int start, int end)
{
	if (n == 1)
	{
		return 0;
	}
	vector<vector<pair<int, int>>> g;

	vector<int> d;
	deque<int> q;
	int m = edges.size();

	g.resize(2 * n);
	d.resize(2 * n);

	for (int i = 0; i < 2 * n; i++) d[i] = 3 * m;
	for (int i = 0; i < n; i++)
	{
		g[i].push_back({ i + n, 1 });
		g[i + n].push_back({ i, 1 });
	}

	for (int i = 0; i < m; i++)
	{
		int a = edges[i].first, b = edges[i].second, t = edge_type[i];

		a--; b--;

		if (t)
		{
			g[a + n].push_back({ b + n, 0 });
			g[b + n].push_back({ a + n, 0 });
		}
		else
		{
			g[a].push_back({ b, 0 });
			g[b].push_back({ a, 0 });
		}
	}

	int u = start, v = end; u--, v--;
	int sol1 = shortest_path(d, q, u, v, g, m);
	int sol2 = shortest_path(d, q, u, v + n, g, m);
	return min(sol1, sol2);
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);

	int n, m; cin >> n >> m;
	vector<pair<int, int>> e(m);
	vector<bool> b(m);
	for (int i = 0; i < m; i++)
	{
		int x;
		cin >> e[i].first >> e[i].second >> x;
		b[i] = x;
	}
	int start, end; cin >> start >> end;
	cout << solve(e, b, n, start, end) << "\n";

	return 0;
}