#include <bits/stdc++.h>
#define ll long long
using namespace std;

#define INF 1000000000
int main()
{
    int n, m;cin>>n>>m;
    vector<vector<pair<int, int>>> graph(n+1);
    for(int i = 0; i<m; i++)
    {
        int x, y, b;cin>>x>>y>>b;
        graph[x].push_back({y, b});
        graph[y].push_back({x, b});
    }

    int start, finish;cin>>start>>finish;

    priority_queue<pair<int, int>> q;
    vector<pair<int, int>> paths(n+1, {INF, -1});
    //vector<bool>proc(n+1, false);

    paths[start]={0,0};
    q.push({start, 0});

    while(!q.empty())
    {
        auto vrh = q.top();
        q.pop();
        //if(proc[abs(vrh.first)])continue;
        //proc[abs(vrh.first)]=true;
        //for(int i = 1; i<=n; i++)
            //cout<<paths[i].first<<" ";
        //cout<<"\n";
        vrh.first = abs(vrh.first);
        //cout<<vrh.first<<"\n";
        for(auto u : graph[vrh.first])
        {
            int tp = paths[vrh.first].first + (paths[vrh.first].second!=u.second);
            if(tp<paths[u.first].first)
            {
                paths[u.first] = {tp, u.second};
                q.push({(-1) * u.first, u.second});

            }
        }
    }
    if(paths[finish].first==INF)
        cout<<"-1";
    else
        cout<<paths[finish].first;

    return 0;
}