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

struct node
{
    int MIN=INT_MAX;
    vector<int> links;
    vector<bool> linktype;
};

node icebergs[200001];

void explore(int current, int prev, bool machine, bool change, int M, int L)
{
    if (current!=M)
    {
        icebergs[current].MIN = min(icebergs[current].MIN, icebergs[prev].MIN + change);
    }
    if (current !=L)
    {
        for (int j=0; j<icebergs[current].links.size(); j++)
        {
            int next = icebergs[current].links[j];
            if (next!=prev && icebergs[next].MIN > (icebergs[current].MIN + change))
            {
                change = (machine == icebergs[current].linktype[j]);
                machine = icebergs[current].linktype[j];
                explore(next, current, machine, change, M, L);
            }
        }
    }
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n, m;
    cin >> n >> m;
    for (int i=0; i<m; i++)
    {
        int a, b;
        bool t;
        cin >> a >> b >> t;
        t++;
            icebergs[a].links.push_back(b);
            icebergs[a].linktype.push_back(t);
            icebergs[b].links.push_back(a);
            icebergs[b].linktype.push_back(t);
    }
    int M, L;
    cin >> M >> L;
    icebergs[M].MIN=0;
    explore(M, 0, 0, 0, M, L);
    if (icebergs[L].MIN==INT_MAX)
        cout << -1;
    else
        cout << icebergs[L].MIN;
    return 0;
}