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

#define ios ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define ll long long
#define ull unsigned long long
#define inf INT_MAX
#define llinf LLONG_MAX
#define mt make_tuple
#define mp make_pair
#define parll pair<ll,ll>
#define parii pair<int,int>
#define frs first
#define sec second
#define neparno(x) (x&1)
#define parno(x) (!neparno(x))
#define lowbit(x) (x&-x)
#define nzd __gcd
#define nzs(e1,e2) (e1/nzd(e1,e2))*e2
#define all(V) V.begin(),V.end()
#define fill(V,v) fill(all(V),v)
#define l_b(BRL,brl) lower_bound( BRL.begin(), BRL.end(), brl )-BRL.begin()-1
#define u_b(BRU,bru) upper_bound( BRU.begin(), BRU.end(), bru )-BRU.begin()
#define mxn 200004

struct grana
{
    ll v;
    ll t;
};

struct element
{
    ll c;
    ll p;
    ll t;
};

ll n,m,a,b,R[mxn],T[mxn];
vector <grana> G[mxn];
vector <bool> V(mxn,false);
queue <element> Q;

void Set()
{
    for ( ll i = 1; i <= n; i++ )
    {
        R[i] = llinf;
    }
}

void BFS( ll root )
{
    R[root] = 0;
    Q.push({root,root,0});
    while ( !Q.empty() )
    {
        ll i = Q.front().c;
        ll p = Q.front().p;
        ll t = Q.front().t;
        Q.pop();
        V[i] = true;
        for ( auto x : G[i] )
        {
            ll next = x.v;
            if ( next != p )
            {
                if ( R[i]+(x.t!=T[i]) < R[next] || !V[next] )
                {
                    Q.push({next,i,x.t});
                }
                if ( R[i]+(x.t!=T[i]) < R[next] )
                {
                    R[next] = R[i]+(x.t!=T[i]);
                    T[next] = x.t;
                }
            }
        }
    }
}

void DFS( ll i )
{
    V[i] = true;
    for ( auto x : G[i] )
    {
        ll next = x.v;
        if ( !V[next] )
        {
            DFS(next);
        }
    }
}

bool Nepovezano()
{
    fill(V,false);
    DFS(a);
    return (!V[b]);
}

int main()
{
    ios;

    cin >> n >> m;
    ll u,v,t;
    bool kecevi = true;
    for ( ll i = 1; i <= m; i++ )
    {
        cin >> u >> v >> t;
        if ( t == 0 )
        {
            kecevi = false;
        }
        G[u].push_back({v,t});
        G[v].push_back({u,t});
    }
    cin >> a >> b;

    if ( Nepovezano() )
    {
        cout << "-1\n";
        return 0;
    }
    if ( kecevi )
    {
        cout << "1\n";
        return 0;
    }

    Set();
    BFS(a);

    cout << R[b];

    return 0;
}