#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define PI acos(-1)
#define LSB(i) ((i) & -(i))
#define ll long long
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define sc second
#define th third
#define fo fourth
#define pii pair<int,int>
#define pll pair<ll,ll>
#define ldb double
#define MOD 1000000007
#define endl "\n"

#define all(data)       data.begin(),data.end()
#define TYPEMAX(type)   std::numeric_limits<type>::max()
#define TYPEMIN(type)   std::numeric_limits<type>::min()
#define ima_li_te(D,d)  find(all(D),d)
#define MAXN 200007
vector<pll> adj[MAXN];
ll d0[MAXN],d1[MAXN];
void Dijkstra(ll s,ll n)
{
    for(ll i=1;i<=n;i++) d0[i]=d1[i]=LLONG_MAX;
    d0[s]=0,d1[s]=1;
    priority_queue<pair<pll,ll>,vector<pair<pll,ll>>,greater<pair<pll,ll>>> q;
    q.push(mp(mp(0,1),s));
    while(!q.empty())
    {
        ll v=q.top().sc,u0=q.top().fi.fi,u1=q.top().fi.sc; q.pop();
        if(u0==d0[v] && u1==d1[v])
        {
            for(auto x:adj[v])
            {
                ll y=x.fi,len=x.sc;
                bool check=false;
                ll z0,z1;
                if(len==0) {z0=0; z1=1;}
                else if(len==1) {z0=2; z1=1;}
                if(min(d0[v]+z0,d1[v]+z1)<d0[x.fi])
                {
                    d0[x.fi]=min(d0[v]+z0,d1[v]+z1);
                    check=true;
                }
                if(len==0) {z0=1; z1=2;}
                else if(len==1) {z0=1; z1=0;}
                if(min(d0[v]+z0,d1[v]+z1)<d1[x.fi])
                {
                    d1[x.fi]=min(d0[v]+z0,d1[v]+z1);
                    check=true;
                }
                if(check) q.push(mp(mp(d0[x.fi],d1[x.fi]),x.fi));
            }
        }
    }
}
int main()
{
    ios::sync_with_stdio(false); cin.tie(0);
    ll n,m,a,b,t; cin>>n>>m;
    for(int i=0;i<m;i++)
    {
        cin>>a>>b>>t;
        adj[a].pb(mp(b,t));
        adj[b].pb(mp(a,t));
    }
    ll u,v; cin>>u>>v;
    Dijkstra(u,n);
    ll rez=min(d0[v],d1[v]);
    if(rez==LLONG_MAX) cout<<-1<<endl;
    else cout<<rez<<endl;
    return 0;
}