#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mp make_pair
#define F first
#define S second
#define all(v) v.begin(), v.end()
#define LPRINT(a, b) for (auto&(a) : (b))
#define li(i,a,b) for (int (i) = (a); (i) < (b); (i)++)
#define lij(i,a,b) for (int (i) = (a); (i) <= (b); (i)++)

//vraca indeks
int bs(vector<int> a, int target, int n) {
	int l = 0, r = n - 1;
	int ans = -1;
	while (l <= r) {
		int mid = l + (r - l) / 2;
		if (a[mid] >= target) {
			ans = mid;
			r = mid - 1;
		}
		else {
			l = mid + 1;
		}
	}
	return ans;
}


int main()
{


	unordered_set<int> visited;
	int n, m;
	cin >> n >> m;
	vector<vector<int>> adj(n, vector<int>(n, -1));
	vector<pair<ll, ll>> bestPath(n, { LONG_MAX,LONG_MAX });
	for (int i = 0; i < m; i++) {
		int a, b, t;
		cin >> a >> b >> t;
		adj[a-1][b-1] = t;
		adj[b-1][a-1] = t;
	}
	int u, v;
	cin >> u >> v;
	u--; v--;
	bestPath[u] = { 0,LONG_MAX - 1 };

	for (int i = 0; i < n; i++) {
		int lowestCost = LONG_MAX;
		int lowestCostVertex = -1;
		for (int j = 0; j < n; j++) {
			if (visited.count(j) == 0 && min(bestPath[j].first, bestPath[j].second) < lowestCost) {
				lowestCost = min(bestPath[j].first, bestPath[j].second);
				lowestCostVertex = j;
			}
		}

		visited.insert(lowestCostVertex);
		for (int j = 0; j < n; j++) {
			if (visited.count(j) == 0 && adj[lowestCostVertex][j] > -1) {
				if (adj[lowestCostVertex][j] == 0) {
					bestPath[j].first = min(bestPath[j].first, min(bestPath[lowestCostVertex].second + 1, bestPath[lowestCostVertex].first));
				}
				else {
					bestPath[j].second = min(bestPath[j].second, min(bestPath[lowestCostVertex].first + 1, bestPath[lowestCostVertex].second));
				}

			}
		}
	}
	int res = min(bestPath[v].first, bestPath[v].second);
	if(res==LONG_MAX) cout<<-1;
	else cout<<res;

	return 0;
}