#include<bits/stdc++.h>
#define ll long long
#define MAXN 200007
using namespace std;
vector<vector<pair<ll,ll>>>G(MAXN);
bool visited[MAXN]={};
ll dist[MAXN];
vector<ll>k;
void dfs(ll node, int d)
{
    visited[node]=true;
    dist[node]=d;
    for(auto i:G[node])
    {
        if(!visited[i.first])
        {
            if(i.second==d%2) dfs(i.first,d);
            else k.push_back(i.first);
        }
    }
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    ll n,m;
    cin>>n>>m;
    while(m--)
    {
        ll x,y,z;
        cin>>x>>y>>z;
        G[x].push_back({y,z});
        G[y].push_back({x,z});
    }
    ll u,v;
    cin>>u>>v;
    vector<ll>x={u};
    ll d=0;
    for(ll i=0;i<=n;i++) dist[i]=LLONG_MAX;
    while(!empty(x))
    {
        for(auto i:x) dfs(i,d);
        x.clear();
        for(auto i:k)
        {
            if(dist[i]==LLONG_MAX) x.push_back(i); 
        }
        d++;
        k.clear();
    }
    if(dist[v]==LLONG_MAX) cout<<-1<<endl;
    else cout<<dist[v]<<endl;
}