#include <bits/stdc++.h>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n, m;
    cin>>n>>m;
    list<pair<int, int>> graf[n+1];
    while(m--){
        int a, b, t;
        cin>>a>>b>>t;
        graf[a].push_back(make_pair(b, t));
        graf[b].push_back(make_pair(a, t));
    }
    int pocetak, kraj;
    cin>>pocetak>>kraj;
    vector<pair<int, int>> niz(n+1, make_pair(INT_MAX, 0));
    niz[pocetak] = make_pair(0, 0);
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    pq.push(make_pair(0, pocetak));

    while(!pq.empty()){
        int k = pq.top().second;
        pq.pop();

        list<pair<int, int>>::iterator i;
        for(i=graf[k].begin();i!=graf[k].end();++i){
            int j = i->first;
            int led = i->second;
            int zbir = niz[k].first + (niz[k].second != led);
            if(niz[j].first > zbir){
                niz[j] = make_pair(zbir, led);
                pq.push(make_pair(zbir, j));
            }
        }
    }
    if(niz[kraj].first != INT_MAX)
        cout<<niz[kraj].first;
    else
        cout<<-1;
    return 0;
}