#include <bits/stdc++.h>
using namespace std;
const int mn=200100;
vector<vector<pair<int,int> > > graf(mn);
int a[mn];
int b[mn];
bool visited[mn];
void dfs(int nodara,int kraj)
{
    if(visited[nodara]) return;
    visited[nodara]=true;
    queue<int> q;
    q.push(nodara);
    while(!q.empty())
    {
        int node=q.front();
        visited[node]=true;
        q.pop(); 
        for(int i=0;i<graf[node].size();i++)
        {
            if(visited[graf[node][i].first]) continue;
            //cout<<graf[node][i].first<<endl;
            if(graf[node][i].second==0 && a[graf[node][i].first]==-1)
            {
                if(b[node]!=-1 && a[node]!=-1) a[graf[node][i].first]=min(a[node],b[node]+1);
                else if(a[node]==-1) a[graf[node][i].first]=b[node]+1;
                else a[graf[node][i].first]=a[node];
            }
           if(graf[node][i].second==1 && b[graf[node][i].first]==-1)
            {
                if(b[node]!=-1 && a[node]!=-1) b[graf[node][i].first]=min(b[node],a[node]+1);
                else if(b[node]==-1) b[graf[node][i].first]= a[node]+1;
                else b[graf[node][i].first]=b[node];
                //uradi za b
            }
            if(graf[node][i].second==0 && a[graf[node][i].first]!=-1)
            {
                if(a[node]!=-1 && b[node]!=-1)a[graf[node][i].first]=min(a[graf[node][i].first],min(a[node],b[node]+1));
                else if(a[node]!=-1) a[graf[node][i].first]=min(a[graf[node][i].first],a[node]);
                else a[graf[node][i].first]=min(a[graf[node][i].first],b[node]+1);
                //uradi za b
            }
            if(graf[node][i].second==1 && b[graf[node][i].first]!=-1)
            {
                //a[graf[node][i].first]=min(a[graf[node][i].first],min(a[node]));
                if(a[node]!=-1 && b[node]!=-1) b[graf[node][i].first]=min(b[graf[node][i].first],min(a[node]+1,b[node]));
                else if(a[node]!=-1) b[graf[node][i].first]=min(b[graf[node][i].first],a[node]+1);
                else b[graf[node][i].first]=min(b[graf[node][i].first],b[node]);
                //uradi za b
            }
            if(!visited[graf[node][i].first]) q.push(graf[node][i].first);
        }
    }
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        a[i]=-1;
        b[i]=-1;
    }
    for(int i=0;i<m;i++)
    {
        int u,v,t;
        cin>>u>>v>>t;
        graf[u].push_back(make_pair(v,t));
        graf[v].push_back(make_pair(u,t));
    }
    int poc,kraj;
    cin>>poc>>kraj;
    a[poc]=0; 
    b[poc]=-1;
    dfs(poc,kraj);
    /*cout<<a[1]<<" "<<b[1]<<endl;
    cout<<a[2]<<" "<<b[2]<<endl;
    cout<<a[3]<<" "<<b[3]<<endl;
    cout<<a[4]<<" "<<b[4]<<endl;*/
    if(a[kraj]==-1 && b[kraj]==-1) cout<<-1<<endl;
    else if(a[kraj]==-1) cout<<b[kraj]<<endl;
    else if(b[kraj]==-1) cout<<a[kraj]<<endl;
    else cout<<min(a[kraj],b[kraj])<<endl;
}