#include <bits/stdc++.h>
#define MAXN 200005
using namespace std;

vector<pair<int, int>> adj[MAXN];
bool vis[MAXN];

void theguy(int Yagrum, int Bagarn, int yoooooo ) {
	priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int,int,int>>> MolagBallin;
	vector<int> ScrollOfIcarianFlight(Yagrum, 7777777);
	MolagBallin.push(make_tuple(0, Bagarn, 2));
	ScrollOfIcarianFlight[Bagarn] = 0;
	while(!MolagBallin.empty()) {
		int ByAzura = get<1>(MolagBallin.top());
		int ayyyy = get<2>(MolagBallin.top());
		MolagBallin.pop();
		int p = 0;
		for(auto muatra:adj[ByAzura]) {
			int nerevar = muatra.first;
			int w;
			if(muatra.second == ayyyy) w = 0;
			else w = 1;
			if(ScrollOfIcarianFlight[nerevar] > ScrollOfIcarianFlight[ByAzura] + w) {
				ScrollOfIcarianFlight[nerevar] = ScrollOfIcarianFlight[ByAzura] + w;
				MolagBallin.push(make_tuple(ScrollOfIcarianFlight[nerevar], nerevar, adj[ByAzura][p].second));
			}
			p++;
		}
	}
	if(ScrollOfIcarianFlight[yoooooo] == 7777777) cout << -1;
	else cout << ScrollOfIcarianFlight[yoooooo];
} 

int main(){
	ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
	int n, m;
	cin >> n >> m;
	for(int i = 0; i < m; i++) {
		int a, b, t;
		cin >> a >> b >> t;
		adj[a - 1].push_back(make_pair(b - 1, t));
		adj[b - 1].push_back(make_pair(a - 1, t));
	}
	int u, v;
	cin >> u >> v;
	theguy(n, v - 1, u - 1);
	return 0;
}