#include <iostream>
#include <bits/stdc++.h>

using namespace std;

typedef pair<int, int> par;

int main()
{
    int n, m, i, a, b, t, j, u, v;
    cin >> n >> m;
    vector<par> graf[n+1];
    for(i=0; i<m; i++)
    {
        cin >> a >> b >> t;
        graf[a].push_back(make_pair(b, t));
        graf[b].push_back(make_pair(a, t));
    }
    cin >> u >> v;

    int resenje[n+1];
    int znak[n+1];
    for(i=1; i<=n; i++)
    {
        resenje[i]=INT_MAX;
        znak[i]=0;
    }

    priority_queue<par, vector<par>, greater<par> > prioritetniRed;
    prioritetniRed.push(make_pair(0, u));
    resenje[u] = 0;
    znak[u]=0;
    int u1, v1;
    bool nadjen = false;
    vector<par>::iterator it;
    while (!prioritetniRed.empty() && !nadjen)
    {
        u1 = prioritetniRed.top().second;
        prioritetniRed.pop();
        //cout << "OD " << u1 << endl;
        for(it = graf[u1].begin(); it != graf[u1].end(); it++)
        {
            v1 = (*it).first;
            t = (*it).second;
            if(resenje[u1]+(t!=znak[u1])<resenje[v1])
            {
                resenje[v1] = resenje[u1] + (t!=znak[u1]);znak[v1] = t;
                prioritetniRed.push(make_pair(resenje[v1], v1));
            }
            if(v1==v)
            {
                nadjen = true;
                break;
            }
            //cout << "OD " << u1 << " OBIDJEN " << v1 << endl;
        }
    }
    if(resenje[v]==INT_MAX)
    {
        resenje[v]=-1;
    }
    cout << resenje[v] << endl;
}