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

struct c {
    constexpr bool operator()(
        pair<int, int> const& a,
        pair<int, int> const& b)
        const noexcept
    {
        return a.second < b.second;
    }
};

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;

    //vector<bool> visited(n+1, false);
    vector<pair<int, int>> paths(n+1, {1000000001, -1});
    priority_queue <int> dfs;

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

    while(!dfs.empty())
    {
        int vert = dfs.top();
        dfs.pop();
        //visited[vert]=1;

        for(auto g : graph[vert])
        {
            int tp = paths[vert].first + (paths[vert].second!=g.second);
            if(tp<paths[g.first].first)
            {
                paths[g.first].first=tp;
                paths[g.first].second = g.second;
                dfs.push(g.first);
            }

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

    return 0;
}