#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];
    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;
    while (!prioritetniRed.empty())
    {
        u1 = prioritetniRed.top().second;
        prioritetniRed.pop();
        for(auto it = graf[u1].begin(); it != graf[u1].end(); it++)
        {
            v1 = (*it).first;
            t = (*it).second;
            if(resenje[v1]>resenje[u1]+(t!=znak[u1]))
            {
                resenje[v1] = resenje[u1] + (t!=znak[u1]);znak[v1] = t;
                prioritetniRed.push(make_pair(resenje[v1], v1));
            }
        }
    }
    if(resenje[v]==INT_MAX)
    {
        resenje[v]=-1;
    }
    cout << resenje[v] << endl;
}