// I may fail a thousand times
// But there is no giving up
// IOI - here I come
#include <bits/stdc++.h>
using namespace std;
const int N=2e5;
vector<int> g[N+5][2];
deque<pair<int,int>> dq;
int dist[N+5][2];
void solve(){
	int n,m;cin>>n>>m;
	for(int i=1;i<=m;i++){
		int u,v,w;
		cin>>u>>v>>w;
		g[u][w].push_back(v);
		g[v][w].push_back(u);
	}
	for(int i=1;i<=n;i++)dist[i][0]=dist[i][1]=1e9;
	int x,y;cin>>x>>y;
	dist[x][0]=0;
	dq.push_front({x,0});
	for(;!dq.empty();){
		auto it=dq.front();dq.pop_front();
		int v=it.first,k=it.second;
		for(int u:g[v][k]){
			if(dist[u][k]>dist[v][k]){
				dist[u][k]=dist[v][k];
				dq.push_front({u,k});
			}
		}
		if(dist[v][k]+1<dist[v][1-k]){
			dist[v][1-k]=dist[v][k]+1;
			dq.push_back({v,1-k});
		}
	}
	int ans=min(dist[y][0],dist[y][1]);
	if(ans>=1e9)ans=-1;
	cout<<ans<<'\n';
}
signed main(){
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	int t=1;
	for(;t;t--){
		solve();
	} 	
	return 0;
}